我有这个过滤器来设置URL中的所有帖子标题: -
add_filter( 'sanitize_title', 'wpse52690_limit_length', 1, 3 );
function wpse52690_limit_length( $title, $raw_title, $context ) {
// filters
if( $context != 'save' )
return $title;
// vars
$desired_length = 100; //number of chars
$desired_words = 50; //number of words
$prohibited = array(
'the'
,'in'
,'my'
,'etc'
//put any more words you do not want to be in the slug in this array
);
// do the actual work
// filter out unwanted words
$_title = explode( ' ', $title );
//if you want more than one switch to preg_split()
$_title = array_diff( $_title, $prohibited );
// count letters and recombine
$new_title = '';
for( $i=0, $count=count($_title); $i<$count; $i++ ) {
//check for number of words
if( $i > $desired_words )
break;
//check for number of letters
if( mb_strlen( $new_title.' '.$_title[$i] ) > $desired_length )
break;
if( $i != 0 )
$new_title .= ' ';
$new_title .= $_title[$i];
}
return $new_title;
}
当我插入一个超过20个单词的标题时,它不会在标题中插入所有单词。
有什么理由?
答案 0 :(得分:0)
我已经测试了这个功能,它运行正常。
所以会发生什么是你的标题超过了$desired_length
中设置的100个字符的限制。
如果您想要总共最多50个单词,您可能希望将$desired_length
增加到更大的数量--500,600或类似的东西。
请注意,网址不得超过2000个字符,因为它们会被您的网络浏览器拒绝,而且不会加载。
修改强>
尝试更改:
if( mb_strlen( $new_title.' '.$_title[$i] ) > $desired_length )
到
if( mb_strlen( $new_title.' '.$_title[$i], "UTF-8" ) > $desired_length )