Adding Span to Title (5 posts)

  1. swellness
    Posted 4 years ago #

    I need to know how to add a span tag to a post title. What I need to accomplish is to have the first word of each title be a different color then the remaining words. I know it's possible as it is accomplished on this blog.


    Could anyone help me? I would very much appreciate it.


  2. Michael
    Forum Moderator
    Posted 4 years ago #

    for just the page title, edit page.php and replace the_title(); with:

    $words = explode(' ', the_title('', '',  false));
    $words[0] = '<span>'.$words[0].'</span>';
    $title = implode(' ', $words);
    echo $title;

    or for generally all titles (this will add the span around the first word in any title, such as post titles, page titles, and the_title is also used for instance in page lists) -
    add something like this to functions.php of your theme:

    add_filter('the_title', 'span_first_word');
    function span_first_word($title) {
    $words = explode(' ', $title);
    $words[0] = '<span>'.$words[0].'</span>';
    $title = implode(' ', $words);
    return $title;
  3. swellness
    Posted 4 years ago #

    Oh my that worked like a charm! Thank you so much I thought I was going to have to stew over this for hours. I very much appreciate you time!

  4. kdubya16
    Posted 4 years ago #

    Any way on how to target all instances of 'the' within a the_title();?

    Any feedback would be greatly appreciated, Thanks!

  5. kendawes
    Posted 4 years ago #

    Hi Sweeper,

    That is most excellent!! I have been looking for something like this!

    How would I restrict this to only work on Page and Post titles?


Topic Closed

This topic has been closed to new replies.

About this Topic