修改了Wordpress功能,将Span放在Title的第一个单词周围?

时间:2012-04-21 23:00:46

标签: php wordpress preg-replace

我正在尝试使用一个函数,在Wordpress网站的每个帖子标题的第一个单词周围添加“span”,并找到this extremely similar个问题。当H2元素中有链接时,第二个答案中的函数可以正常工作。

但是在我的网站中,我没有使用帖子标题作为链接,因此找到的解决方案不起作用。我试图想出一个新的preg-replace模式,以便跳过链接部分的检测,但是无法获得它。

基本上,我想要这个:

<h2><?php the_title(); ?></h2> or <h2>Converted post title</h2>

......成为这个:

<h2><span>Converted</span> post title</h2>

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

<?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;
?>

答案 1 :(得分:1)

使用woodpress钩子和过滤器做到这一点的最佳方法。这样你就可以使用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' );

答案 2 :(得分:0)

我建议你在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