Display name of taxonomy once

时间:2019-10-01 作者:Gregory Schultz

只显示一次分类法名称的最佳方式是什么?我使用了一种叫做show_category 它有三类:新闻、评论和未分类。我有六个帖子:三个在新闻中,一个在评论中,两个在未分类中。它们显示如下:

News (name of category in taxonomy) News item 1 News (name of category in taxonomy) News item 2 News (name of category in taxonomy) News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) tes Uncategorized (name of category in taxonomy) test 2

我正在寻找一种方法,在分类法中只使用一次类别名称,如下所示:

News (name of category in taxonomy) News item 1 News item 2 News item 3 Reviews (name of category in taxonomy) Review item Uncategorized (name of category in taxonomy) Tes Test 2

我的循环代码:

<?php $postcount=0; while ( have_posts() ) : the_post(); 
$terms = wp_get_post_terms( get_the_ID(), \'show_category\');
foreach ($terms as $t):
echo $t->name;
endforeach;?>
<div id="<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_title();?>
</div>
<?php endwhile; ?>

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

不是最好的,但对我来说效果很好:(你可以用这个代替问题中的内容)

$postcount = 0;

//global $wp_query; // Uncomment if necessary.
// Group the posts by category.
$groups = [];
foreach ( $wp_query->posts as $i => $p ) {
    $terms = wp_get_post_terms( $p->ID, \'show_category\' );
    foreach ( $terms as $t ) {
        if ( ! isset( $groups[ $t->term_id ] ) ) {
            $groups[ $t->term_id ] = [];
        }
        $groups[ $t->term_id ][] =& $wp_query->posts[ $i ];
    }
}

// And display the posts under their own category. Note though, that a post may
// appear twice if it\'s assigned to multiple categories.
global $post;
foreach ( $groups as $term_id => $posts ) {
    $term = get_term( $term_id );

    // Display the term/category name.
    echo \'<h3>\' . esc_html( $term->name ) . \'</h3>\';

    // And the category\'s posts.
    foreach ( $posts as $post ) {
        setup_postdata( $post );
        ?>
            <div id="<?php the_ID(); ?>" <?php post_class(); ?>>
                <?php the_title(); ?>
            </div>
        <?php
    }
}
wp_reset_postdata();
PS:Theh3 标记只是示例。。

相关推荐

Skip latest 3 posts from loop

我下载了一个初学者主题(下划线)。我想从索引页的循环中排除前3篇文章。这是循环;<?php if ( have_posts() ) : if ( is_home() && ! is_front_page() ) : ?> <header> <h1 class=\"page-title screen-reader-text\"><?php sing