此循环返回每个帖子的类别,并多次显示。相反,我只想显示一次类别,这是按类别过滤的功能。
<div id="filter-box" class="filter-box">
<?php
$args = array (
'post_type' => "post",
'post_status' => "publish",
'order' => 'ASC',
'orderby' => 'title' ,
'posts_per_page' => -1);
$all_query = new WP_Query($args);
if ($all_query->have_posts()):
while ($all_query->have_posts()):
$all_query->the_post();
?>
<a href="#" class="filter-btn" data-cat="<?php get_cat($post->ID); ?>"><?php get_cat($post->ID); ?></a>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</div>
这是来自functions.php的功能
function get_cat($post_id) {
$category_detail=get_the_category($post_id);
foreach($category_detail as $cd) {
echo $cd->cat_name;
}
}
每个类别只显示一次类别。
答案 0 :(得分:0)
请将您的代码修改为:
<?php
$args = array (
'post_type' => "post",
'post_status' => "publish",
'order' => 'ASC',
'orderby' => 'title' ,
'posts_per_page' => -1);
$all_query = new WP_Query($args);
$tempArr = array();
if ($all_query->have_posts()):
while ($all_query->have_posts()):
$all_query->the_post();
if(!in_array($post->ID , $tempArr)){ // check if array has ID not display
array_push($tempArr, $post->ID); //push postID in array
?>
<a href="#" class="filter-btn" data-cat="<?php get_cat($post->ID); ?>"><?php get_cat($post->ID); ?></a>
<?php
}
endwhile;
endif;
wp_reset_postdata();
?>
说明::请将数组声明为$tempArr = array();
,然后检查$temArr
数组是否具有该postID(如果没有),然后显示类别并将其推入数组。