I've been trying to create a sidebar widget to display recent comments from specific category. I'm having difficulties in determining how Wordpress knows from which categories the comments are.
I have checked the codex on get_comments
function but it doesn't seem to allow fetching from specific categories. I've found some hints from Kovshenin's blog, but can't seem to make it work properly, because my try either shows all comments (disregarding the categories) or doesn't show it at all.
I'm basing the widget from Widget_Recent_Comments
(found from wp-includes/default-widgets.php
). Here is what I have so far. I believe the output is controlled around this area:
$output = '';
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Recent Comments' ) : $instance['title'], $instance, $this->id_base );
if ( empty( $instance['number'] ) || ! $number = absint( $instance['number'] ) )
$number = 5;
$category_name = empty( $instance['category_name'] ) ? '' : $instance['category_name'];
$comments = get_comments( apply_filters( 'widget_comments_args', array( 'number' => $number, 'status' => 'approve', 'post_status' => 'publish' ) ) );
$output .= $before_widget;
if ( $title )
$output .= $before_title . $title . $after_title;
$output .= '<ul id="recentcomments">';
if ( $comments ) {
foreach ( (array) $comments as $comment) {
$output .= '<li class="recentcomments">' . /* translators: comments widget: 1: comment author, 2: post link */ sprintf(_x('%1$s on %2$s', 'widgets'), get_comment_author_link(), '<a href="' . esc_url( get_comment_link($comment->comment_ID) ) . '">' . get_the_title($comment->comment_post_ID) . '</a>') . '</li>';
}
}
$output .= '</ul>';
$output .= $after_widget;
echo $output;
And here is the full codes: http://pastebin.com/VH666jty
Basically my widgets is similar to the default Recent Comments widget. Only that it has an optional Display comments only from category/categories: ...
, where user could input by themselves.
Leaving it blank will display comments from all category, while putting some category slug, separated by comma (e.g.: mycategory,othercategory
) will display comments only from those selected categories.