A Simple Helper to Check if a Post Has Comments or Pingbacks

A previous post, I shared a strategy on how to separate comments, trackbacks, and pings in a WordPress post.

In short, the article covered how to create a template such that the comments would be listed first, then the trackbacks and pings would be listed second.

In addition to creating templates that separate the types of comments related to a post, I also find it useful to have a helper function to determine if a given post has comments and/or pingbacks.

How To Check if a Post Has Comments

The main reason for sharing code like this is because I think that it helps to do two things:

  1. Abstract domain logic into its own area of the application (or, in this case, a theme),
  2. It makes the code that’s leveraging it a easier to read within the context of the template

I’ll explain what I mean by the above two points after the code, but first, here’s the helper function that I use to help heck if a post has comments, trackbacks, or pings:

Simple, right?

Some would argue that abstracting just these few lines into their own function is overkill.

Obviously I disagree, primarily because this helps to make the front end code more readable. On top of that, it’s wrapping code that we may be calling multiple times into a single point of maintenance – this is a good thing.

The function is also written in such a way that it’s meant to be more readable than the code it actually contains.

When you write it out, it would go something like this:

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

Or this:

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

And then, if you were to read it aloud, it would read something like:

  • if this theme has pingbacks,
  • if the theme has comments,
  • …and so on.

Anyway, it’s a quick helper function that I’ve used in a couple of projects that I’ve found to be useful, and that makes it a bit easier to understand what’s going on in the comments template.


I’m a bit fan of naming functions like that. It definitely makes things a lot more readable. Thanks Tom!

Hi Tom,
I read often your posts, but always via Feed. Please can you enhance the feed with your gists. Currently is the feed without your code examples or a link to the gist. This is not useful on reading the content.
A hint, a short helper: https://github.com/inpsyde/Inpsyde-oEmbed-Gist

Frank – thanks for the heads up on this. I’ll aim to take care of it this week :).

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>