I am trying to wrap a around the first word of multiple word widget titles. I have used the answer from here:
https://stackoverflow.com/questions/10263792/revised-wordpress-function-to-put-a-span-around-the-first-word-of-the-title
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> ";
unset($ARR_title['0']);
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:
https://stackoverflow.com/questions/10833435/wrap-b-tag-around-first-word-of-string-with-preg-replace
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:
the_title();
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
if(isset($title_parts[1]))
$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:
widget_title();
that is making this function act funny?