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

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

Example for WordPress title

Read More
<h2 class="entry-title"><a href="#">Welcome to WordPress</a></h2>

I want to be like this

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

the function

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

May i know what to put on the preg_replace

Related posts

Leave a Reply

2 comments

  1.   $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. 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 frontend for instance, will look like this:

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

    But it won’t be affected on the backend while viewing the posts table.

    And then you can style it in your style.css like this for instance:

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

    EDIT: added if else statement to adjust formatting for frontend theme only without adjusting backend theme. Seems to work just fine. If there is a better way, I’d love to hear it, Thanks!