我有以下标准循环,用于返回自定义帖子类型的标题:
<ul>
<?php
$args = array(
'post_type' => 'food_types',
'posts_per_page' => -1
);
$query = new WP_Query($args);
while ($query->have_posts()) : $query->the_post(); ?>
<li><?php echo the_title();?></li>
<?php endwhile;
wp_reset_postdata();
?>
</ul>
问题是经常有标题相同的帖子。
我需要修改我的循环,以使循环中返回的任何给定帖子标题只有一个实例。
例如,如果有带有这些标题的帖子...
Tomato
Orange
Orange
Apple
Apple
Egg
Banana
Banana
...然后循环应仅返回以下内容:
Tomato
Orange
Apple
Egg
Banana
我希望这是有道理的。
答案 0 :(得分:0)
数据库中是否存在重复项,如果没有,那么您可能需要运行脚本来删除重复项,因为这可能会导致性能下降。
如果列表中没有太多项目,那么针对您当前代码的快速解决方案可以简单地将每个标题添加到数组中,如果先前已添加项目,则继续while循环。
使用:https://www.php.net/manual/en/function.array-push.php和https://www.php.net/manual/en/function.in-array.php
所以是这样。NB:这只是概念上的...我没有测试代码。
this.scrollPosition
*已修改为使用注释中所述的get_the_title()
答案 1 :(得分:0)
the_title()
不需要回显。检查:
<ul>
<?php
$args = array(
'post_type' => 'food_types',
'posts_per_page' => -1
);
$query = new WP_Query($args);
while( $query->have_posts() ) : $query->the_post(); ?>
<li><?php the_title();?></li>
<?php endwhile;
wp_reset_postdata(); ?>
</ul>
答案 2 :(得分:0)
如果您只担心水果名称,则可以为它创建一个单独的数据集,甚至不必费心循环所有帖子并消除在循环内跟踪名称的负担。
$args = array(
'post_type' => 'food_types',
'posts_per_page' => -1
);
$query = new WP_Query($args);
// Simply build a list of post titles
$fruits = array_column( $query->posts, 'post_title'); // PHP7+
// Get unique values
$fruits = array_unique( $fruits );
// Then all you have to do is loop that list
foreach($fruits as $fruit) : ?>
// Echo shorthand
<li><?= $fruit;?></li>
<?php endforeach;
wp_reset_postdata();