![](/img/trans.png)
[英]How can I make this code search only for posts and not pages? (wp_query)
[英]How can I make this Php WP_Query returning categories only once?
此循环返回每个帖子的类别,并多次显示。 相反,我只想显示类别,这是按类别过滤的功能。
<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;
}
}
希望只显示一次类别,因为每个帖子只显示一次。
请修改您的代码为:
<?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(如果没有),然后显示类别并将其推送到数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.