Cheesetoast

Brain Food for Web Developers

Speech Bubble

Comments Bubble on WordPress Titles

You may have seen a lot of blogs where the number of comments associated with a particular post is displayed subtly next to the post title. I’m going to quickly go through how this can be done with a WordPress child theme without too much trouble.

First of all you need to open up the functions.php file in your child theme. If you have no idea what a child theme is then you can have a read of my previous posting about WordPress child themes. Once you have this file open you need to create a new function called ‘childtheme_override_postheader_posttitle()’. This new function will (as you may have guessed) override the parent theme’s postheader_posttitle function, which is used to display the title for each post. The function will be almost identical to that of it’s predecessor, but with one new line of code.

The new line of code is as follows:
if (get_comments_number() != FALSE) { $posttitle .= “<sup>” . get_comments_number() . “</sup>”; };

Easy! This line uses the built-in WordPress function ‘get_comments_number()’ to retrieve the number of comments associated with the current post. If this number is NOT false, i.e. is not 0, then we’ll display the number we have just recieved. Note: If you’re interested in the comments number function then you should also take a look at comments_number(), a simliar function that displays the number of comments directly.

To display the number of comments for each post we’re going to add it to the $posttitle variable by using .= (which concatenates the content). For this example I’ve chosen to display the number in the HTML superscript tag ‘<sup>’ which will raise the number up a little. Now I can add the graphic of a speech bubble (or whatever I want) to the sup tag.

Here is the complete code for the entire function:

function childtheme_override_postheader_posttitle() {

if (is_single() || is_page()) {

$posttitle = ‘<h1>’ . get_the_title() . “</h1>\n”;

} elseif (is_404()) {

$posttitle = ‘<h1>’ . __(‘Not Found’, ‘thematic’) . “</h1>\n”;

} else {

$posttitle = ‘<h2><a href=”‘;

$posttitle .= apply_filters(‘the_permalink’, get_permalink());

$posttitle .= ‘” title=”‘;

$posttitle .= __(‘Permalink to ‘, ‘thematic’) . the_title_attribute(‘echo=0′);

$posttitle .= ‘” rel=”bookmark”>';

$posttitle .= get_the_title();

if(get_comments_number() != FALSE) { $posttitle .= “<sup>”. get_comments_number().”</sup>”; };

$posttitle .= “</a></h2>\n”;

}

return apply_filters(‘thematic_postheader_posttitle’,$posttitle);

}

Have fun playing around with it!

 

Author: Graham

My name is Graham and I'm a Scottish web developer living in California. I love working with clean code to make attractive and usable websites. I'm also interested in cooking, gardening, and taekwondo.

Comments are closed.