如何从评论者的自定义帖子中显示类别名称

时间:2016-12-23 作者:Pete

我有一段代码可以显示评论者的帖子标题。我想显示帖子类别。我尝试了post\\u标题的每一个排列,试图显示类别,但没有成功。

<?php 
$args = array(
\'post_type\' => array( \'post\' ),
\'post_status\' => array( \'publish\' ),    
\'author\' => $comment->user_id,
\'orderby\' => \'post_date\',
\'order\' => \'ASC\',
\'posts_per_page\' => 1
);
$comment_author_posts = get_posts( $args );
if ($comment_author_posts):
foreach ( $comment_author_posts as $comment_author_post ): ?>
<a href="<?php echo get_permalink( $comment_author_post->ID ) ?>"><i class="fa fa-users" aria-hidden="true"></i>
<?php echo $comment_author_post->post_title ?></a>

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

您可以使用get_the_category

这可以通过使用setup_postdata( $comment_author_post ) 或者通过使用$comment_author_post->ID

USING setup_postdata()

$args = array(
    \'post_type\' => array( \'post\' ),
    \'post_status\' => array( \'publish\' ),
    \'author\' => $comment->user_id,
    \'orderby\' => \'post_date\',
    \'order\' => \'ASC\',
    \'posts_per_page\' => 1
);
$comment_author_posts = get_posts( $args );
if ($comment_author_posts):
    foreach ( $comment_author_posts as $comment_author_post ):
        setup_postdata( $comment_author_post );
        $categories = get_the_category();
        ?>
        <a href="<?php echo get_permalink( $comment_author_post->ID ) ?>"><i class="fa fa-users" aria-hidden="true"></i>
        <?php echo esc_html( $categories[0]->name ); ?></a>

        <?php
    endforeach;
endif;

USING $comment_author_post->ID

$args = array(
    \'post_type\' => array( \'post\' ),
    \'post_status\' => array( \'publish\' ),
    \'author\' => $comment->user_id,
    \'orderby\' => \'post_date\',
    \'order\' => \'ASC\',
    \'posts_per_page\' => 1
);
$comment_author_posts = get_posts( $args );
if ($comment_author_posts):
    foreach ( $comment_author_posts as $comment_author_post ):
        $categories = get_the_category( $comment_author_post->ID );
        ?>
        <a href="<?php echo get_permalink( $comment_author_post->ID ) ?>"><i class="fa fa-users" aria-hidden="true"></i>
        <?php echo esc_html( $categories[0]->name ); ?></a>

        <?php
    endforeach;
endif;

References

get_posts()

get_the_category()