我尝试使用一个函数在Wordpress站点中每个帖子标题的第一个单词周围添加一个“跨度”,然后发现了this extremely similar问题。当H2元素中有一个链接时,第二个答案中的函数工作得很好。
但在我的网站中,我没有使用帖子标题作为链接,所以找到的解决方案不起作用。我试着想出一个新的preg-replace模式,以跳过对链接部分的检测,但还没能实现。
基本上,我想要这样:
<h2><?php the_title(); ?></h2> or <h2>Converted post title</h2>..。变成这样:
<h2><span>Converted</span> post title</h2>发布于 2012-04-22 08:04:14
要做到这一点,最好的方法是使用木版压力机挂钩和过滤器。以便无需额外代码即可使用the_title()函数。
将此代码放入主题文件夹中的functions.php中。就这样。
function add_label_to_post_title( $title = '' ) {
if(trim($title) != "")
{
$ARR_title = explode(" ", $title);
if(sizeof($ARR_title) > 1 )
{
$first_word = "<span>".$ARR_title['0']."</span>";
unset($ARR_title['0']);
return $first_word. implode(" ", $ARR_title);
}
else
{
return "<span>{$title}</span>";
}
}
return $title;
}
add_filter( 'the_title', 'add_label_to_post_title' );发布于 2012-04-22 07:09:17
您可以使用类似以下内容:
<?php
$title = get_the_title();
if(substr($title,0)>-1){
$first_word = substr($title,0,strpos($title," "));
$after_that = substr($title,strpos($title," ")+1);
}else{
$first_word = $title;
$after_that = "";
}
echo "<span>".$first_word."</span> " . $after_that;
?>发布于 2012-04-22 07:48:04
我建议你在javascript中这样做,这样你就可以减少服务器的处理/cpu使用。你仍然会得到同样的结果。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('h2.title').each( function (){
var obj_h2 = $(this);
var h2_title = obj_h2.html();
var words = h2_title.split(' ');
words[0] = '<span>' + words[0] + '</span>'
obj_h2.html( words.join( ' ' ) );
} );
});
</script>https://gist.github.com/2440296#file_h2_span1stw_2.htm
*以前的代码版本..https://gist.github.com/2440296#file_h2_span1stw.htm http://jsbin.com/uguhel/edit#html,live
https://stackoverflow.com/questions/10263792
复制相似问题