Revised Wordpress function to put a Span around the first word of the Title?

admin

Administrator
Staff member
I'm trying to use a function that adds a "span" around the first word of every post title in a Wordpress site, and found <a href="https://stackoverflow.com/questions...on-to-put-a-span-around-the-first-word-of-the">this extremely similar</a> question. The function in the second answer works fine when there's a link inside the H2 element.

But In my site, I'm not using the post title as a link, so the found solution doesn't work. I've tried to come up with a new preg-replace pattern, as to skip the detection of the link part, but haven't been able to get it.

Basically, I want this:

Code:
&lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; or &lt;h2&gt;Converted post title&lt;/h2&gt;

... to become this:

Code:
&lt;h2&gt;&lt;span&gt;Converted&lt;/span&gt; post title&lt;/h2&gt;