Adding A Line Break in The Title

Sometimes a post title breaks in an odd way. Say you have a long title, and you want to break it into two lines. This little snippet will show you how to add a line break <br> in the title of your WordPress post or page.

The Problem

Your title is too long, or it breaks in odd places.

Screenshot of a book title that breaks in an odd place
Our book title breaks in an odd place

Technically speaking, you can add a <br /> tag right in the title, and WordPress will detect it as a line break. But what if we want the line break in the single.php template and not in the archive.php template? This is what we’ll have.

Screenshot of adding a br tag in the title
Adding a <br /> tag in the title works
Screenshot of the title breaking in the archive page
It doesn’t look good in the archive page!

The Solution

We can give WordPress the ability to detect a special character in the_title. Choose a special character that you don’t normally use in a title; a pipeline | for example. Then, we can simply use a function to replace the pipeline character with a line break tag for the single.php. And use the same function to replace the pipeline with a blank space for the archive.php template.

<?php echo str_replace(' | ', '<br />', get_the_title()); ?>
A screenshot of adding a pipeline special character to replace it with a line break
Screenshot of a book title that breaks in a better way
That’s much better!
<?php echo str_replace(' | ', ' ', get_the_title()); ?>
A screenshot of a better title in the archive page
Much better in the archives as well!

Source: How to add a line break in a WordPress post title

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"