KNOWNHOST KNOWLEDGE BASE

Hosting Question? Find the Solution - Browse our Guides, Articles, and How-To's

What are Conditional Tags in WordPress Comments?

Category: WordPress
Tags: # # #

WordPress has a number of conditional tags that evaluate whether something is true or false, then based on the logical value, does one thing or another. Generally, if something is true take action, otherwise do not, then return to whatever it was doing.

A simple example of a conditional tag in WordPress would be to check if someone has visited the homepage, and if so, they

<?php
  if ( is_home()) {
    echo "You have reached the home page";
  }
?>

There aren’t that many conditional tags surrounding comments in WordPress, but there are a couple.

is_comments_popup()

This returns true if you’re inside a WordPress comments popup and can be used as:

  <?php is_comments_popup(); ?>

comments_open()

This returns true if comments are enabled for a particular post id:

  <?php comments_open( $post_id ); ?>

In addition to the conditional tags that operate directly on comments, there are a number of conditionals that work through other sections of the code, such as the $wp_query. Within the query, one can check if the query is dealing with a comment feed or whether there are comments to loop through.

Is the query for a comments feed?

If the query is for a comments feed, return true. Note that you have to run the query before checking, otherwise the query will always return false:

  function is_comment_feed() {
    global $wp_query;
    if ( ! isset( $wp_query ) ) {
      _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not
                                          work before the query is run. Before then,
                                          they always return false.' ), '3.1.0' );
      return false;
    }
    return $wp_query->is_comment_feed();
  }

Are there comments to loop through?

If there are comments, return true, otherwise false.

  function have_comments() {
    global $wp_query;
    return $wp_query->have_comments();
  }

Conclusion

Have a WordPress website? Check out our Managed WordPress Hosting and see if we are a good fit for you. KnownHost offers 365 days a year, 24 hours a day, all 7 days of the week best in class technical support. A dedicated team ready to help you should you need our assistance. You’re not using KnownHost for the best webhosting experience? Well, why not?