How to add a line break in a WordPress post title

Before and after, animated

Sometimes while working a client build, you’ll come across a weird request or three. Even more often, because this is WordPress, there are dozens of ways to accomplish said weird task.

Recently someone asked me to allow custom line breaks inside a WordPress post title (which, if you’re keeping score, doesn’t generally allow markup). Normally I’d argue we should just control this with CSS/widths, but the guy’s layout had some really specific gridding and breaking and I could see the value in his request. Here’s what we did…

The Setup

The plan involved inserting a special character into the title where he wanted the break, so we settled on inserting a vertical pipe “|” as the indicator. The client would enter a title like this:

This is a | title with a | custom break

WordPress is smart enough to not include special characters in the URL, so all that’s left is making our template swap the vertical pipe with a line break.

The Execution

Normally in a WordPress template, when you want to output the title, you’d use the_title() and be on your merry way. In this case, we want to search the title string for vertical pipes before we output it. Something like this should do the trick:

<?php echo str_replace(' | ', '<br />', get_the_title()); ?>

That str_replace function accepts three arguments, the value to search for, the value to replace it with when found, and the subject string (in this case, our title) to operate on.

Our function finds vertical pipes in the title and replaces them with a <br> before outputting. Perfect!