Skip to content

How To Check If A Post Has Comments, Pingbacks Or Trackbacks

WordPress has have_comments(); conditional tag to check if a post has comments in it. It’s easy to create a comments.php file for your theme to show comments using this tag, but there’s no such tag like this for checking if a post has pingbacks or trackbacks.

A theme which shows comments and pings in a different area makes a site more readable. Here’s how to check if a post has comments, pingbacks or trackbacks. And this snippet helps in checking if a post has pingbacks or trackbacks:

function acme_post_has( $type, $post_id ) {

$comments = get_comments('status=approve&type=' . $type . '&post_id=' . $post_id );
$comments = separate_comments( $comments );

return 0 < count( $comments[ $type ] );

}

You need to post the above function in your theme’s functions.php file.

Now you can check if a post has comments by adding:

if ( acme_post_has( 'comments', $post->ID ) ) { }

And you can check if the post has trackbacks and pingbacks by adding following:

if ( acme_post_has( 'pings', $post->ID ) ) { }

The type of comment(s) to display. Can be ‘all’, ‘comment’, ‘trackback’, ‘ping back’, or ‘pings’. ‘pings’ is both ‘trackback’ and ‘ping back’ together.

I recently used this function in a theme that was developing. That theme is currently under review, and if everything goes right we will soon see it on the WordPress.org.

Leave a Reply

Your email address will not be published. Required fields are marked *