Revised Wordpress function to put a Span around th

2019-05-31 16:04发布

I'm trying to use a function that adds a "span" around the first word of every post title in a Wordpress site, and found this extremely similar question. The function in the second answer works fine when there's a link inside the H2 element.

But In my site, I'm not using the post title as a link, so the found solution doesn't work. I've tried to come up with a new preg-replace pattern, as to skip the detection of the link part, but haven't been able to get it.

Basically, I want this:

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

... to become this:

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

3条回答
Ridiculous、
2楼-- · 2019-05-31 16:55

Best way to do that using woodpress hooks and filter. so that you can use the_title() function without additional code.

put this code into functions.php in your theme folder. that's all.

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' );
查看更多
家丑人穷心不美
3楼-- · 2019-05-31 16:57

I suggest you do that in javascript so you could lessen the processing/cpu use of the server. You would still have the same result.

<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

*Previous code version.. https://gist.github.com/2440296#file_h2_span1stw.htm http://jsbin.com/uguhel/edit#html,live

查看更多
\"骚年 ilove
4楼-- · 2019-05-31 17:06

You can use something like this:

<?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;
?>
查看更多
登录 后发表回答