山滚云

限制WordPress文章标题字数方法

功能代码 279℃

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’);

转载请注明:⎛蜗牛建站⎞ » 限制WordPress文章标题字数方法

蜗牛建站是专业的wordpress网站建设服务团队,我们有丰富的wordpress网站建设经验,可以提供wordpress网站建设、网站改版、主题开发、wordpress外贸建站等服务。

城市分站:深圳建站公司北京网站建设上海网站建设广州网站建设深圳网站建设成都网站建设重庆网站建设武汉网站建设

业务范围:深圳建站公司,网站优化,虚拟主机    微信:ganshangwoniu    QQ:549233124    业务咨询热线:177-2050-9380

   Copyright © 2008-2024 蜗牛建站版权所有   

QQ在线咨询
wordpress主题开发公司微信号