WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to wrap a around the first word of multiple word widget titles. I have used the answer from here:


and adjusted it to look like:

function add_label_to_post_title( $title = '' ) {
    $ARR_title = explode(" ", $title);

    if(sizeof($ARR_title) > 1 ) {
        $first_word = "<span>".$ARR_title['0']."</span> ";
        return $first_word. implode(" ", $ARR_title);
    } else {
        return $title;

add_filter( 'widget_title', 'add_label_to_post_title' );
add_filter( 'the_title', 'add_label_to_post_title' );

and it works great on two word titles. However 3 or more word titles are not affected.

I tried modifying the code with:

preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<span>$0</span>', $string);

from here:


and had the same result, works great on two word titles but three or more are not affected. Does anyone have any idea why?

I am also using this for:


And it works xactly as expected. Also if I use:

echo add_label_to_post_title('any multiple word string with more than two words');

it also works exactly as expected.

I tried using:

add_filter('widget_title', my_title);

function my_title($title) {
// Cut the title to 2 parts
$title_parts = explode(' ', $title, 2);

// Throw first word inside a span
$title = '<span class="my_class">'.$title_parts[0].'</span>';

// Add the remaining words if any
    $title .= ' '.$title_parts[1];

return $title;

from Insert a span inside widget title to give a different color to the second word and I had the same result, it worked for up to 2 word strings but 3 or more words it does not work.

Does any one know what it is about the:


that is making this function act funny?

share|improve this question

You should check out the filters assigned to widget_title

    global $wp_filter;
    printf('<h2>Debug:</h2><pre>%s</pre>',print_r( $wp_filter['widget_title'],true));

to see if there is anything unusual.

Also try the Twenty Twelve theme (I don't see this behaviour there) and deactive all plugins.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.