【问题标题】:Get the current post category name inside while loop在while循环中获取当前帖子类别名称
【发布时间】:2019-06-23 15:04:58
【问题描述】:

我创建了一个自定义帖子类型“stm_media_gallery” 以及此自定义帖子类型中的三个类别。 我想显示与每个帖子关联的类别名称。

<?php $gallery_query = new WP_Query( array('post_type' => 
'stm_media_gallery', 'posts_per_page' => -1) );
 if( $gallery_query->have_posts() ) : 
 while( $gallery_query->have_posts() ) : $gallery_query->the_post(); ?>
      --Display post name and its category name
 <?php endif; ?>
 <?php endwhile; ?>

【问题讨论】:

标签: php wordpress categories posts


【解决方案1】:

把这个放到While循环中

  global $post;
  $postcat = get_the_category( $post->ID );

【讨论】:

    【解决方案2】:

    您只需将以下代码放入循环中:

    <div>
    <?php 
        foreach((get_the_category()) as $category){
            echo $category->name."<br>";
            echo category_description($category);
            }
        ?>
    </div>
    

    更新现有代码

        <?php $gallery_query = new WP_Query( 
          array('post_type' => 'stm_media_gallery',
           'posts_per_page' => -1) );
    
     if( $gallery_query->have_posts() ) : 
     while( $gallery_query->have_posts() ) : $gallery_query->the_post(); 
    
        $gallery_category = get_the_category( get_the_ID() );
    
        the_title( '<h3>', '</h3>' ); 
        echo "<br>";
      <?php foreach ( $gallery_category as $key => $value) { echo $value->category_nicename; } ?>
    
    
     <?php endif; ?>
     <?php endwhile; ?>
    

    【讨论】:

    • get_the_category() 仅适用于category 税。在这种情况下,我们需要wp_get_post_terms()
    • 选中“gallery_category”时返回空数组
    【解决方案3】:

    您可以使用WordPress预制功能the_category( $separator, $parents, $post_id )将帖子类别打印为链接。

    有关 WordPress Codex 的更多信息:Function Reference: the_category

    编辑:仅打印名称:

    $categories = get_the_category();
    
    if ( ! empty( $categories ) ) {
        echo esc_html( $categories->name );   
    }
    

    【讨论】:

    • 我需要帖子类别名称而不是链接
    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 2023-04-05
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2017-07-22
    • 2011-03-19
    相关资源
    最近更新 更多