How do you write a Wordpress function to put Span around the first word Title?

I want to replace the first word in the title with the <span></span>inside.

WordPress example

<h2 class="entry-title"><a href="#">Welcome to Wordpress</a></h2>

I want to be like that

<h2 class="entry-title"><a href="#"><span>Welcome</span> to Wordpress</a></h2>

function

function span_on_title($span) {
 return preg_replace('', '', $span, 1);
}
add_filter('the_title','span_on_title');

Can i find out what to wear preg_replace

+3
source share
2 answers
  $title = '<h2 class="entry-title"><a href="#">Welcome to Wordpress</a></h2>';

  $title = preg_replace('/<a([^>]+)>([a-zA-Z]+)\s/i', '<a$1><span>$2</span> ', $title);

  return $title;
+2
source

Add this to your functions.php file in your theme:

// Adds span around the first word of post titles
if ( ! is_admin(false) ) {
add_action('brentini_span_post_title');
function brentini_span_post_title($span_title) {
$span_title = preg_replace('/(^[A-z0-9_]+)\s/i', '<span>$1</span> ', $span_title);
return $span_title;
}
add_filter('the_title', 'brentini_span_post_title');
} 
elseif ( ! is_admin(true) ) {
remove_filter('the_title', 'brentini_span_post_title');
}

The output on the interface, for example, will look like this:

<h2 class="entry-title"><a href="#"><span>Welcome</span> to Wordpress</a></h2>

But this will not affect the backend when viewing the message table.

And then you can create a style in your style.css style, for example, like this:

h2.entry-title span {color:#0531C2}

EDIT: , else frontend . , . , , !

+1

Source: https://habr.com/ru/post/1760188/


All Articles