我希望在自定义循环中获得唯一类别的简单列表(仅循环中帖子的类别)。我一直在摸索一些代码,下面是我得到的:
<?php
    $args = array(
        \'post_status\'=>\'publish\',
        \'post_type\'=>\'post\',
        \'posts_per_page\'=>-1
    );
    $get_posts = new WP_Query();
    $get_posts->query($args);
    if($get_posts->have_posts()) {
    $cats = array();
    while($get_posts->have_posts()) { $get_posts->the_post();
            $post_categories = wp_get_post_categories( get_the_ID() );
            $i = 0;
            foreach($post_categories as $c){
                $cat = get_category( $c );
                $cats[$i] = $cat->slug ;
                $i++;
            }
        } //endwhile
        $result = array_unique($cats);
       print_r($result);
    } //endif
    wp_reset_postdata();
?>
 这将把每个帖子类别放入一个数组中,我可以打印出来。但我想合并每个帖子的类别数组,删除重复项(因此每个唯一类别只有一个实例),然后能够打印出来。
本质上,我想要完成的是为这些类别创建一个下拉列表,以便通过使用所选类别刷新循环来按特定类别进行排序。我可以处理其余的,我只需要得到一个循环中所有帖子的唯一、不重复的类别列表。
有人有什么想法吗?
非常感谢Jonah
 
                    最合适的回答,由SO网友:Chris Quinn 整理而成
                    编辑:已移动$i = 0 在圈外。这将为您提供完整的类别列表。
$get_posts = new WP_Query();
$i = 0;
$get_posts->query($args);
if($get_posts->have_posts()) {
    $cats = array();
    while($get_posts->have_posts()) { $get_posts->the_post();
        $post_categories = wp_get_post_categories( get_the_ID() );
        foreach($post_categories as $c){
            $cat = get_category( $c );
            $cats[$i] = $cat->slug ;
            $i++;
        }
    } //endwhile
    $result = array_unique($cats);
    print_r($result);
} //endif
wp_reset_postdata();
 基本上,它将嵌套数组展平
$cats - 我想
array_unique 可能已丢弃类别,因为它们具有相同的键。