最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

filters - Shorten the title length

programmeradmin2浏览0评论

So I'm using this filter in order to shorten the title:

function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();

if ( $length && is_numeric($length) ) {
    $title = substr( $title, 0, $length );
}

if ( strlen($title)> 0 ) {
    $title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
    if ( $echo )
        echo $title;
    else
        return $title;
}
}

and in my template:

 <?php the_titlesmall('', '...', true, '50') ?>

This works like a charm.

However, this filter adds "..." to every post title, even if the post title is under "50" characters and it looks weird. How can I only add the "..." to the titles that are over "50" characters?

Thanks a lot!

So I'm using this filter in order to shorten the title:

function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();

if ( $length && is_numeric($length) ) {
    $title = substr( $title, 0, $length );
}

if ( strlen($title)> 0 ) {
    $title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
    if ( $echo )
        echo $title;
    else
        return $title;
}
}

and in my template:

 <?php the_titlesmall('', '...', true, '50') ?>

This works like a charm.

However, this filter adds "..." to every post title, even if the post title is under "50" characters and it looks weird. How can I only add the "..." to the titles that are over "50" characters?

Thanks a lot!

Share Improve this question edited May 14, 2015 at 1:14 fuxia 107k39 gold badges255 silver badges459 bronze badges asked May 14, 2015 at 0:58 JohannJohann 8674 gold badges14 silver badges31 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Try this. First check if the original string length is less than or equal to passed in length, and if so, we ignore the $after parameter :

function the_titlesmall($before = '', $after = '', $echo = true, $length = false) { $title = get_the_title();
    if( strlen($title) <= $length )
         $after = '';
    if ( $length && is_numeric($length) ) {
        $title = substr( $title, 0, $length );
    }

    if ( strlen($title)> 0 ) {
        $title = apply_filters('the_titlesmall', $before . $title . $after, $before, $after);
        if ( $echo )
            echo $title;
        else
            return $title;
    }

}

Instead of having it be an "after" variable, add the ... where you are cutting the substring. Check the length of the string first, and if it's greater than 50, add ... when you cut the substring, in that line.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论