Style WordPress Titles Based on Number of Letters

Wordpress How-To's

A common problem that I’ve encountered – how to control dynamic text based on how long it is. In this case I had titles ranging from 10 characters to 25 characters – this includes spaces. The goal is to make them centered regardless of how many letters and spaces are in the title.

Here is an example of one of the shorter titles I was given:

Here is an example of one of the longer titles I was given:

A series of quick if/else statements and use of the strlen function in PHP allows me to assign different classes depending on the length of the dynamic title. I figured out, based on the CSS on the H1 class, that 14 was my magic number.

Here’s the quick snippet of code I used:

{code type=php}
$title = $post->post_title;
$char_title = strlen($title);
if ($char_title > 14) {$header_style = “double”;}
else {$header_style = “single”;}{/code}

I grab the post title using common WordPress calls and make it into the $title variable. The I use the strlen function to determine the number of characters (including spaces) in the title. If it’s greater than 14, it assigns the $header_style variable the class “double” or else it assigns it the “single” class.

Here is how I used it within the WordPress loop:

{code type=php}


Hopefully you’ve found this quick tutorial valuable. Contact me if you have any questions or would do it a different way. There’s 1,001 ways to do everything – that’s why I love coding.

What's the Buzz?

Andy is a true professional who is one of the most capable people I have ever worked with. His enthusiasm for his job is impressive and his ability to adapt and evolve to a new task is incredible. He is one of those rare people who you can tell where you want to get to and he can engineer the path there for you and give you extra choices along the way. His ability to learn new skills, willingness to continue to grow and expand is astounding. He’s also very skilled at what he does now and has a great eye for design and usability, blending form and function with class. And he’s fun to spend time with.

- Claire Devereux Thompson
Sterling Advertising