【问题标题】:How to show a category name even when there is no post in Wordpress即使 Wordpress 中没有帖子,如何显示类别名称
【发布时间】:2019-02-01 02:28:02
【问题描述】:

我试图在我的分类页面中显​​示 WordPress 类别名称,但每次该类别没有 post 时,它的名称都不会显示。我怎么能显示它,即使它是空的?

<?php

 $term = get_queried_object();
 $term->slug;
 $terms = get_the_terms($post->ID, 'productcat');
 $nameTerm = $terms[0]->name;
 $linkTerm = get_term_link($terms[0]);

?>

<span><?php echo $nameTerm ?></span>

【问题讨论】:

    标签: wordpress categories


    【解决方案1】:
     // Prior to WordPress 4.5.0
    
          $terms = get_terms( 'product_cat', array(
              'hide_empty' => false,
         ) );
    
     // Since WordPress 4.5.0
    
          $terms = get_terms( array(
              'taxonomy' => 'product_cat',
              'hide_empty' => false,
         ) );
    

    在这种情况下,您可以检查此代码

      $taxonomy_text = "";
      $cat_list = get_the_term_list( $post->ID, 'product_cat', '<strong>In this post:</strong> ', ', ', '' );
    
      if ( '' != $cat_list ) {
            $taxonomy_text .= "$cat_list<br />\n";
      }
    

    【讨论】:

      【解决方案2】:

      听起来您想要获取该类别的所有术语,而不仅仅是帖子术语。使用get_terms。您可以通过hide_empty 显示没有帖子的类别。

      <?php
       $term = get_queried_object();
       $term->slug;
       $terms = get_terms( 'product_cat', array(
          'hide_empty' => false,
       ) );
       $nameTerm = $terms[0]->name;
       $linkTerm = get_term_link($terms[0]);
      ?>
      <span><?php echo $nameTerm ?></span>
      

      【讨论】:

      • 始终确保不超过一个if(count($terms) &gt; 1)
      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多