4

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

Example for Wordpress title

<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

2 Answers 2

2
  $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;
4
  • hmmm.. nothing change when I put the code. I've update the_title format with hyperlink
    – iamafish
    Aug 17, 2010 at 21:48
  • 1
    @Michael - Not as you wrote it ;) ... You are missing $title as the 3rd argument of preg_replace ( php.net/manual/en/function.preg-replace.php ) - working example ==> codepad.org/LHkvfNIf Aug 17, 2010 at 22:03
  • @Michael actually this one worked, but need modify all template which have the the_title(). BTW thanks give me a clue. Good example.
    – iamafish
    Aug 17, 2010 at 22:44
  • No problem, happy to be able to help :) Aug 17, 2010 at 22:53
1

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!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.