【问题标题】:Display Top category only in WordPress仅在 WordPress 中显示顶级类别
【发布时间】:2021-04-21 21:57:19
【问题描述】:

我有一些属于多个类别的帖子。我为它们中的每一个都定义了一个顶级类别,我想只在我的类别页面上显示这个顶级类别。不幸的是,它显示了所有归类。 (例如,此类别页面上的第一篇文章:https://www.la-strada.net/rubrique/muzik-zak/)。 一个开发者提供了一个应该有帮助的函数,但它是一个很长的镜头......

https://gist.github.com/LucasDemea/afa5d58c8e9ed0d71b7b2523d84bcce9

我的观点是使用的主题(Qode Bridge)使用自己的术语来命名 WP 元素,因此代码没有正确调用它们。 对此有何想法?

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:

    您链接的脚本实际上正在运行,但您必须在前端调用它。

    如果您想要更直接的方式在循环中获取它们,您可以执行以下操作:

    <?php
    if( have_posts() ): // ... loop starting
      while( have_posts() ): the_post();
    
        // ... get our post categories
        $categories = get_the_category(); // ... get post categories
        foreach( $categories as $category ) {
          if ( $category->parent == 0 ) { // ... if the category has no parent
            echo '<p>' . $category->cat_name . '</p>'; // ... display the category name
          };
        };
    
        the_title( '<h1>', '</h1>' );
    
      endwhile;
    endif; // ... loop ending
    ?>
    
    Function Description
    get_the_category Retrieves post categories.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多