我正在尝试使用一个函数,在Wordpress网站中每个帖子标题的第一个单词周围添加一个"span",并发现了这个极其相似的问题。当 H2 元素内有链接时,第二个答案中的函数工作正常。
但是在我的网站上,我没有使用帖子标题作为链接,因此找到的解决方案不起作用。我试图想出一种新的预置替换模式,以跳过链接部分的检测,但无法获得它。
基本上,我想要这个:
<h2><?php the_title(); ?></h2> or <h2>Converted post title</h2>
。成为这个:
<h2><span>Converted</span> post title</h2>
使用木压钩和过滤器的最佳方法。 这样您就可以使用 the_title() 函数而无需额外的代码。
将此代码放入函数中.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' );
你可以使用这样的东西:
<?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;
?>
我建议你在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.htmhttp://jsbin.com/uguhel/edit#html,live