Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using get_comments('status=approve&number=5') to display recent comments in my wordpress sidebar. I need to display the recent comments of a particular category. How to do this?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

In this link, there is the following code that addresses your question:

// Posts per page setting
$ppp = get_option('posts_per_page'); // either use the WordPress global Posts per page setting or set a custom one like $ppp = 10;
$custom_offset = 0; // If you are dealing with your custom pagination, then you can calculate the value of this offset using a formula

// category (can be a parent category)
$category_parent = 3;

// lets fetch sub categories of this category and build an array
$categories = get_terms( 'category', array( 'child_of' => $category_parent, 'hide_empty' => false ) );
$category_list =  array( $category_parent );
foreach( $categories as $term ) {
 $category_list[] = (int) $term->term_id;
}

// fetch posts in all those categories
$posts = get_objects_in_term( $category_list, 'category' );

$sql = "SELECT comment_ID, comment_date, comment_content, comment_post_ID
 FROM {$wpdb->comments} WHERE
 comment_post_ID in (".implode(',', $posts).") AND comment_approved = 1
 ORDER by comment_date DESC LIMIT $ppp OFFSET $custom_offset";

$comments_list = $wpdb->get_results( $sql );

if ( count( $comments_list ) > 0 ) {
 $date_format = get_option( 'date_format' );
 echo '<ul>';
 foreach ( $comments_list as $comment ) {
 echo '<li>Comment: '.substr( $comment->comment_content, 0, 50 ).'..<br />'.date( $date_format, strtotime( $comment->comment_date ) ).'<br />Post: <a href="'.get_permalink( $comment->comment_post_ID ).'">'.get_the_title( $comment->comment_post_ID ).'</a></li>';
 }
 echo '</ul>';
} else {
 echo '<p>No comments</p>';
}
?>
share|improve this answer
    
It's Working. Thanks –  Sam Hanson Jan 30 '13 at 4:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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