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

烈酒焚心 提交于 2020-01-02 06:11:09

问题


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


回答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!



来源:https://stackoverflow.com/questions/3507003/how-do-you-write-a-wordpress-function-to-put-a-span-around-the-first-word-of-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!