WordPress自动截取文章标题字数的4种方法

话说在制作WordPress主题的时候,我们通常要截取固定字数的文章标题,以保证主题样式的某些需求。

wpdaxue.com-201304558

下面,倡萌就和大家分享下WordPress自动截取文章标题字数的4种方法。

使用wp_trim_words()截取

WordPress 3.3 新增了一个 wp_trim_words() 函数,专门用来截取限定字数的内容,比如文章、摘要、标题等,使用方法请看:https://www.wpdaxue.com/wp_trim_words.html

通过原生函数截取

将下面的代码添加到主题的 functions.php 文件:

function customTitle($limit) {
    $title = get_the_title($post->ID);
    if(strlen($title) > $limit) {
        $title = substr($title, 0, $limit) . '...';
    }
 
    echo $title;
}

然后在输出文章标题的地方,使用下面的代码:

<?php customTitle(30); ?>

注:30为标题字数,请根据自己的需求修改。如果标题字数小于30,就显示完整标题;如果字数大于30,就截取30个字符,末尾自定添加…

通过自定义函数截取

//标题截断
function cut_str($src_str,$cut_length){$return_str='';$i=0;$n=0;$str_length=strlen($src_str);
		while (($n<$cut_length) && ($i<=$str_length))
		{$tmp_str=substr($src_str,$i,1);$ascnum=ord($tmp_str);
		if ($ascnum>=224){$return_str=$return_str.substr($src_str,$i,3); $i=$i+3; $n=$n+2;}
        elseif ($ascnum>=192){$return_str=$return_str.substr($src_str,$i,2);$i=$i+2;$n=$n+2;}
        elseif ($ascnum>=65 && $ascnum<=90){$return_str=$return_str.substr($src_str,$i,1);$i=$i+1;$n=$n+2;}
        else {$return_str=$return_str.substr($src_str,$i,1);$i=$i+1;$n=$n+1;}
    }
    if ($i<$str_length){$return_str = $return_str . '...';}
    if (get_post_status() == 'private'){ $return_str = $return_str . '(private)';}
    return $return_str;};

将上面的代码添加到主题的 functions.php 最后一个 ?> 的前面,然后在需要调用的地方添加下面的代码即可:

<?php echo cut_str($post->post_title,80); ?>

可以修改上面的数字来设定长度。

通过CSS来“截取”

严格来说,这不是截取,而是隐藏了溢出的字符。对标题所在的选择器 id 或 class 添加下面的样式:

.post-title{
 
width:250px; /* 限制宽度(可选) */
 
white-space:nowrap; /* 禁止自动换行 */
 
overflow:hidden; /* 隐藏溢出的内容 */
 
text-overflow:ellipsis; /* 溢出文本使用...代替 */
 
}

如果你还知道其他截取标题字数的更好方法,欢迎和我们一起分享。

来源:

https://www.wpdaxue.com/wordpress-title-cut-function.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32296.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?