限制WordPress文章标题字数方法

WordPress文章标题太长会导致主题异常并影响美观,很多朋友咨询该如何限制WordPress文章标题长度字数,今天就为大家分享一下限制WordPress文章标题字数方法,包括前端限制及后端编辑器限制。

WordPress 自带的函数是直接输出文章标题长度的,标题太长了就会自动换行,解决办法是使用mbstring函数库来解决,这样就可以指定具体标题字数。

前端限制文章标题字数

function short_title() {

$mytitleorig = get_the_title();

$title = htmlspecialchars($mytitleorig, ENT_QUOTES, "UTF-8");

$limit = "15"; //显示的字数,可根据需要调整

$pad="";

if(strlen($title) >= ($limit+3)) {

$title = mb_substr($title, 0, $limit) . $pad; }

echo $title;

}

调用:short_title(),或者使用以下更简单方法

wp_trim_words(get_the_titlee(),5);

echo wp_trim_words( get_the_title(), 10, '...' );

echo mb_strimwidth(htmlspecialchars_decode(get_the_title()), 0, 50, '...');

现在大部分的 PHP 服务器都支持了 MB 库(mbstring 库 全称是 Multi-Byte String 即各种语言都有自己的编码,他们的字节数是不一样的,目前php内部的编码只支持ISO-8859-*, EUC-JP, UTF-8 其他的编码的语言是没办法在 php 程序上正确显示的。解决的方法就是通过 php 的 mbstring 函数库来解决),所以我们可以放心的使用这个用于控制字符串长度的函数。

备注:如何出现转移乱码等可以采用这个the_title_attribute()替换get_the_title()

后端限制WordPress文章标题

//限制文章标题输入字数

function title_count_js(){

echo '<script>jQuery(document).ready(function(){

jQuery("#titlewrap").after("<div><small>标题字数: </small><input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"title_counter\" readonly=\"\" style=\"background:#fff;\"> <small>最大长度不得超过 46 个字</small></div>");

jQuery("#title_counter").val(jQuery("#title").val().length);

jQuery("#title").keyup( function() {

jQuery("#title_counter").val(jQuery("#title").val().length);

});

jQuery("#titlewrap #title").keyup( function() {

var $this = jQuery(this);

if($this.val().length > 46)

$this.val($this.val().substr(0, 46));

});

});</script>';

}

add_action( 'admin_head-post.php', 'title_count_js');

add_action( 'admin_head-post-new.php', 'title_count_js');

//其它

add_filter( 'the_title', 'wpse_75691_trim_words' );

function wpse_75691_trim_words( $title )

{

// limit to ten words

return wp_trim_words( $title, 10, '' );

}

add_filter( 'the_title', 'wpse_75691_trim_words_by_post_type', 10, 2 );

function wpse_75691_trim_words_by_post_type( $title, $post_id )

{

$post_type = get_post_type( $post_id );

if ( 'product' !== $post_type )

return $title;

// limit to ten words

return wp_trim_words( $title, 10, '' );

}

function limit_word_count($title) {

$len = 5; //change this to the number of words

if (str_word_count($title) > $len) {

$keys = array_keys(str_word_count($title, 2));

$title = substr($title, 0, $keys[$len]);

}

return $title;

}

add_filter('the_title', 'limit_word_count');

Image

联系我们

六翼为您提供更丰富的服务项目,涵盖设计、开发、多媒体、营销、云服务等,驱动品牌网站的互联网创新发展,释放品牌潜力。

联系电话

400-188-6006
010-86469696

在线咨询