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





