Style WordPress Titles Based on Number of Letters


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:

$title = $post->post_title;
$char_title = strlen($title);

if ($char_title > 14) {$header_style = "double";}

else {$header_style = "single";}

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:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="<?php echo $header_style ?>"><h2><?php the_title(); ?></h2></div>
<?php endwhile; endif; ?>

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.

Posted on July 8, 2009 in Wordpress How-To's and has been tagged as , , .

Dropshadow on Text Using Absolute Positioning


Here’s a quick bit of CSS and HTML to achieve a simple dropshadow on text that uses abosolute positioning. This would work great for titles in WordPress. You can adjust the top and left positioning of the .bottom class depending on the offset of dropshadow you want.

(more…)

Posted on July 8, 2009 in CSS Tricks and has been tagged as .


Categories

Services I Offer

About Me

Andy Weigel

My name is Andy Weigel and I'm a web developer and designer in Pittsburgh, PA.

I focus on combining design with technology to build compelling, creative, easy-to-navigate web sites and custom web applications for organizations and businesses of all shapes and sizes. My specialty is WordPress. And most of all, I love what I do!