Styling the First Word

by Sarah Milcetic on December 7th, 2010 in Website Tips2 Comments

CSS doesn’t have a pseudo class for first-word (only first-line and first-letter) but here is a simple tip for WordPress users: You can add a few lines of code to your WordPress theme which allow you to style the first word of any page title differently than the rest of the title. Here’s an example of what it might look like:

Sample of styling the first word

The code:


<?php
$space_pos = strpos(get_the_title(),' ');
$before = '<span class="first-word">';
$after = '</span>';

if($space_pos)
{
$title = $before.get_the_title();
$title = substr_replace($title,$after.' ',$space_pos+strlen($before),1);
}

else $title = $before.get_the_title().$after;
?>

How it works

The first line checks if there is more than one word in the title. If there is, the if statement adds a span with the class “first-word” around the first word. If there is only one word in the title, the else statement adds the span around the entire title. If you want to use something other than a span or give the class a different name, just change the variables for before and after.

How to add it to your theme

  1. Add the above code at the top of your template file.
  2. Replace “<?php the_title(); ?>” with <?php echo $title; ?> in the same document.
  3. Add whatever styling you wish to your CSS file.

Not sure where your theme files are? Look in your WordPress theme folder: wp-content/themes/ then the name of your active theme. Look for a file called page.php for Pages and a file called single.php for Posts. You can add the CSS to the styles.css file in the same directory. For example…

CSS Example


.first-word {
font-style:italic;
font-size:2em;
}

Tags:

2 Responses to “Styling the First Word”

  1. Mike Says:

    Thanks for the help… great piece of code here!

  2. J Says:

    Thanks !!

Leave a Reply