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 the consummate professional. He is sharp, creative, highly-skilled, and extremely responsive.  A true WordPress whiz. We are very pleased with our new website.

- Lauren McKibben
Incline Equity Partners