Optional Markup for Optional Post Titles

Whenever I write a post to publish on a WordPress powered website, I start by crafting a title. While I do this 99.9% of the time, there are definitely situations where no title is needed for a post.

The template tag the_title() already handles these situations really well. In cases where the title field has been left blank this function does nothing. Basically, it works just as I would expect, but it is in the hands of the theme author to ensure that no extra markup is printed if the title field has been left blank.

Here’s some code that you might find in any given theme’s single.php template:


<h2 class="entry-title"><?php the_title(); ?></h2>

In the event that the_title() prints an empty string, the following html will be served to the browser:


<h2 class="entry-title"></h2>

While this may not cause an issue in many themes, there are cases where this can be disruptive. Consider a theme where .entry-title is styled with a background color, border and internal white-space:

In the event that no title is entered for the post, the following may display in the template:

Publishers may not understand why a thin blue box has appeared above their content. They may also wonder how it can be removed. We can stop this confusion before it starts by passing the opening and closing tags as parameters to the_title(). Doing so will allow this markup to be hidden when the title is empty.


<?php the_title( '<h2 class="entry-title">', '</h2>' ); ?>

4 thoughts on “Optional Markup for Optional Post Titles

  1. Great post! I wish more theme authors would start using this method.

    I always used to think that’s how everybody coded titles, even when I knew little about creating themes. The parameters were there, so I used them. Then, I started looking at other themes and wondering why they never used the before and after parameters to output the HTML.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s