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?

Andy is a true top notch programmer with a great eye for design, style and balance. When I out source web development projects, I look for qualified and competent programmers that can understand the big picture, add value throughout entire process, and pays close attention to the details – Andy fits the bill.

Andy is well-versed in web development using various programming languages and CMS platforms. Andy is able to deliver a flawless website based on the creative vision and project requirements. He is able to do it on time and on budget.

I highly recommended Andy as a web developer and give him four stars on his professionalism.

- John LeDonne
LeDonne Creative