How to get WordPress comments by type outside the loop
| By Matt Dunlap on June 7th, 2010 |
Most WordPress themes come with dynamic sidebars for widgets. WordPress has a built in recent comments widget you can use in your sidebar, but you can’t choose what type of comment to return.
Your blog can receive pingbacks or comments. Sometimes when you reference another post on your website, you will create a pingback. I didn’t want pingbacks in my recent comments so I did some searching for sorting by comment type.
There are two ways to get comments in WordPress. Get_comments and wp_list _comments. wp_list_comments allows you to pass a “type” argument while get_comments does not
For wp_list_comments:
(string) The type of comment(s) to display. Can be ‘all’, ‘comment’, ‘trackback’, ‘pingback’, or ‘pings’. ‘pings’ is ‘trackback’ and ‘pingback’ together. Default is ‘all’.
Problem with wp_list_comments is it can only be executed inside the post loop. So, if you want to display recent comments only, no pingbacks, on the home page, you have to use get_comments, and then sort with separate_comments. You can also use get_comments in place of wp_list_comments because you can pass the post_id to get_comments.
How to return only comments using get_comments and separate_comments:
$comments = separate_comments(get_comments('number=20'));
$count=1;
// comment, pingback, trackback, pings
foreach($comments['comment'] as $comm)
{
//get the post from comment
$p = get_post($comm->comment_post_ID);
//get comment author
$author = $comm->comment_author;
//get comment content
$comment = $comm->comment_content;
$count++;
if($count>6)
break;
}
You cannot just pass the number of comment you want to get_comments because if there are any pingbacks, they are ignored in the separate_comments function. Therefore you have to either pass a high number so you know you will get enough comments, or you could just pass on the number argument in get_comments and return them all.




Post a Comment