0

I have this code that displays the commenter's post title. I'd like to display the post category instead. I've tried every permatation of post_title to try to display the category, but with no luck.

<?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

You can use get_the_category

This can be done by either using setup_postdata( $comment_author_post ) or by passing the post ID using $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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.