Aside: Cleaner Titles in WordPress

Quick Tip! What happens when your post title does not fit on one line? It wraps to the second line. What if it’s only one word? And what if that word is “it” or some other shorty? Your title won’t look too nice, eh? Here’s a solution, somewhere inside the loop:

$title = the_title( '<h2>', '</h2>', false );
if ( strlen( $title ) > 0 )
    echo substr_replace( $title, '&nbsp;', strrpos( $title, ' ' ), 1 );

This will look at the last space character in the title and replace it with a non-breaking space character meaning that the last word will always stick to the one before it, hence if the title wraps it’ll be at least two words. Let’s hope the two words are not “is it” :) Anyone know of a CSS solution that can do this?

6 thoughts on “Aside: Cleaner Titles in WordPress

    • Hey Thomas that looks great! Why are you replacing with xC2xA0 and how does this affect the_title() usage in places like the meta title of the page, RSS feeds title, etc.

      The reason I didn’t want to build it around the function is that it may be used in a lot of difference places including ones that don't support HTML, thus they don’t know what nbsp is.

      I also noticed you got some other WordPress related projects in your Github account. I like the admin bar in system colors :)

      Cheers and thanks for your comment!

    • The written (not escaped) character will never make any problems in other output formats like email or RSS as long as it is send in UTF-8. And the hook 'the_title' will not be called outside of theme templates usually.
      I use this plugin for two years now. It just works.

      The admin bar plugin needs a lot of work, it is quite outdated now. I still like the idea. :)

Comments are closed.