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:
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>' ); ?>