Wrap the 2 firsts words of title with a <Span>
-
17-04-2021 - |
Вопрос
I would like to enclose the 2 first word of title inside a to get the following result:
TOP 5 of best photos
I tried using the code below, but it returns only the first word. How can i do to select 2 words?
Thank you
function add_label_to_post_title( $title = '' ) {
if(trim($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}";
}
}
return $title;
} add_filter( 'the_title', 'add_label_to_post_title' );
Решение
You can do that like this:
function add_label_to_post_title( $title = '' ) {
global $post;
if( 'post' == $post->post_type && trim( $title ) != "" ){
$title_words = explode( " ", $title );
$word_count = count( $title_words );
//Sets how many words should be wrapped
$words_to_wrap = 2;
$last_word_index = $word_count > $words_to_wrap ? $words_to_wrap - 1 : $word_count - 1;
$title_words[0] = '<span>' . $title_words[0];
$title_words[ $last_word_index ] = $title_words[ $last_word_index ] . '</span>';
$title = implode( ' ', $title_words );
}
return $title;
}
add_filter( 'the_title', 'add_label_to_post_title' );
You can change the value of $words_to_wrap
to choose how many words should be wrapped in the span element.
If a title has less words than $words_to_wrap
value it would wrap only the available ones.
Не связан с wordpress.stackexchange