我正在查询一个ACF字段,并在前端显示所有结果,如PHP所示:
<ul class="category-menu-items">
<?php
// args
$args = array(
\'numberposts\' => -1,
\'post_type\' => \'wpsc-product\'
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul class="inside-category-menu-items">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="category-menu-item">
<a href="/shop/?view_type=default&product_search=<?php $remove = array(" ", ",", "/", ".", ":", "-", "–", "—", "!", "?", ";");
echo strtolower(str_replace($remove, "+", get_field(\'products_page_designer_name\'))); ?>">
<?php the_field(\'products_page_designer_name\'); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
这很好,唯一的问题是一些字段的值与其他字段的值重复,例如,它将输出如下列表:
Value 01
Value 02
Value 02
Value 03
Value 03
等等,但我只想显示每个实例的一个实例,因此如果有重复的值,它将被隐藏。这有可能吗?如有任何建议,将不胜感激!
最合适的回答,由SO网友:socki03 整理而成
您可以在while循环期间将所有字段传递到一个数组中,去掉该数组中的重复项,然后在该数组上运行foreach循环。它看起来像这样:
<?php
$designers = array();
while ( $the_query->have_posts() ) : $the_query->the_post();
$designers[] = get_field(\'products_page_designer_name\');
endwhile;
// This will strip out any values that are identical.
$designers = array_unique( $designers );
// Run through your unique array of designers
foreach ( $designers as $designer ) { ?>
<li class="category-menu-item">
<a href="/shop/?view_type=default&product_search=<?php
$remove = array(" ", ",","/", ".", ":", "-", "–", "—", "!", "?", ";");
echo strtolower(str_replace($remove, "+", $designer)); ?>">
<?php echo $designer; ?>
</a>
</li>
<?php } ?>
注意,我还没有测试语法或代码。
祝你好运
SO网友:CommandZ
编辑:如果它们具有相同的字段名,则始终返回相同的值
get_field(\'field_name1\')
和
the_field(\'field_name1\')
如果使用相同的field\\u名称,则为相同的值!
查看以下文档:get_field 和the_field.
对于the_field()
上面写着:
这与“echo get\\u field($field\\u name)”相同
一种方法是将then放入一个数组中,然后使用
in_array()
.
相反,我会使用一个类或函数来构建一个具有正确值的对象或数组,然后使用预先设置的值将其提供给模板。Keep the logic out of your template/view!
Essentially what you should want to do is eliminate code reuse as much as possible. 这就是MVC试图实现的目标as well as keeping everything in a logical structure.
他概述的基本内容是:
MVC:控制器从模型中收集数据,传递到视图,而不管理数据。MVC:模型的数据层处理业务/域逻辑。MVC:视图仅表示数据-HTML/CSS但要谨慎No data manipulation胖型,瘦型控制器
For example:
function get_menu_items_object() {
$menu_items = array();
$add_to_menu_items = array(
\'designer_name1\' => get_field(\'products_page_designer_name\'),
\'designer_name2\' => the_field(\'products_page_designer_name\')
);
foreach($add_to_menu_items as $item_key => $item) {
if (!in_array($item, $menu_items)){
$menu_items[$item_key] = $item;
} else {
$menu_items[$item_key] = \'\';
}
return (object) $menu_items;
}
那么你所要做的就是:
$menu_items_object = get_menu_items_object();
echo $menu_items_object->designer_name1; //value echoed
echo $menu_items_object->designer_name2; //value echoed. If \'\' then it is nothing