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:
single-line-title

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}

{/code}

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?

In working with Andy, I was extremely impressed by his overall expertise and the “can-do” attitude with which he approached every phase of the project. While some designers may have become frustrated by working with multiple decision makers with limited web development knowledge, Andy was very understanding and strategic in his approach to finding very organized solutions to address our needs. I would highly recommend him!

- Allison Davies
Ten United