对于很多小伙伴来说WordPress具有着非常折腾的心,今天就有朋友问我如何限制WordPress文章标题长度字数方法,这里我罗列了几种方法,包括前端类型限制WordPress文章标题长度字数方法,与后端编辑器限制WordPress文章标题长度字数方法。
前端限制文章标题字数
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, '...');
备注:如何出现转移乱码等可以采用这个the_title_attribute()替换get_the_title()
<h3>后端限制文章标题字数</h3>
//限制文章标题输入字数
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');