Style the First Word of WordPress Category Titles

WordPress Logo

Posted on April 4, 2015 in Development

One of my latest WordPress projects required a differently styled first word of category titles (as they appear on the frontend of the site). While there are CSS rules that can be used to style the first letter of a word or the first line of a paragraph, there unfortunately is not an equivalent to style the first word of a line of text. It could be achieved with a bit of jQuery magic, but a preferable solution is to use WordPress filters and pre-process the category title before it is displayed on the page.

The below code, which should be put into your theme’s functions.php, will wrap the first word of the category titles in a tag. You can then apply different CSS styling to the span, making the first word of the category title look different. The code could be easily modified to add different tags into the title or change it in some other way.

/** 
 * Add span into category titles, so that the first word can be styled differently
 */ 
function pixelninja_spanify_title($title) {
  // Break the title into words
  $title_words = explode(' ', $title);
  if (count($title_words) > 1) {
    // If the title consists of more than one word, wrap the first word in a  tag
    $title_words[0] = '' . $title_words[0] . '';
    return implode(' ', $title_words);
  } else {
    // If the title is only one word, do not change it
    return $title;
  }
}

/**
 * Custom function to output single category title
 */
function pixelninja_single_cat_title() {
    echo pixelninja_spanify_title(single_cat_title('', false));
}

 

Once you have added the above into your functions, simply call the 2nd function in your theme’s template files to output the modified category title (e.g. in category.php).

If you are using WordPress 4.1+ and the_archive_title() function in your template file to display the archive title based on the queried object, you can leverage the get_the_archive_title filter instead. You can remove the pixelninja_single_cat_title() function from functions.php and instead add the code below:

/**
 * Modify the output of the_archive_title()
 */
function pixelninja_custom_archive_title($title) {
  if ( is_category() ) {
    $title = pixelninja_spanify_title(single_cat_title( '', false ));
  }
  // Here you can add more conditionals and modifications as required, e.g. for Author or Tag pages
  return $title;
}
// Apply the modifying function to the get_the_archive_title filter
add_filter( 'get_the_archive_title', 'pixelninja_custom_archive_title');
Enjoyed this post? Share it with others.
Share on email
Email
Share on facebook
Facebook
Share on google
Google
Share on twitter
Twitter

Leave a reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.