Insert a span inside widget title to give a different color to the second word

I’m trying to make my widget titles two-colored; the first word white and the second one yellow. I have no idea how I can insert a span before the second word of every widget title so that I can put a color to the span.

Related posts

Leave a Reply

3 comments

  1. /**
     * Wraps the first half of the provided string inside a span with the class lol_class.
     *
     * @param  string  $title  The string.
     * @return string          The modified string.
     */
    function wpsa_82312_widget_title($title) {
        // Cut the title into two halves.
        $halves = explode(' ', $title, 2);
    
        // Throw first word inside a span.
        $title = '<span class="lol_class">' . $halves[0] . '</span>';
    
        // Add the remaining words if any.
        if (isset($halves[1])) {
            $title = $title . ' ' . $halves[1];
        }
    
        return $title;
    }
    
    // Hook our function into the WordPress system.
    add_filter('widget_title', 'wpsa_82312_widget_title');
    

    On a recent project, my client wanted graphical headers for the widgets on her WordPress blog. Unfortunately, widgets are not that easily themed. Nor can you do this in CSS.

  2. If it is a text widget, it supports HTML tags (like span). You can use span and other tags in the heading of that widget. Just declare the span CSS of that heading tag in your stylesheet/CSS file.

  3. 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;
    }