首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一次显示分类法的名称

一次显示分类法的名称
EN

WordPress Development用户
提问于 2019-10-01 20:08:33
回答 1查看 43关注 0票数 0

什么是最好的方法,只显示一个分类的名称一次?我使用了一个名为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

我的循环代码:

代码语言:javascript
复制
name;
endforeach;?>
>
EN

回答 1

WordPress Development用户

回答已采纳

发布于 2019-10-01 21:59:16

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

代码语言:javascript
复制
$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 '' . esc_html( $term->name ) . '';

    // And the category's posts.
    foreach ( $posts as $post ) {
        setup_postdata( $post );
        ?>
            >

PS:h3标签只是一些例子。

票数 1
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/349530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档