您可能可以使用sanitize_title
有条件地基于上下文进行挂钩,但我对其他地方还不够熟悉sanitize_title
用来肯定这是一个好的解决方案。诀窍是要限制你的slug,而不包括那些会伤害你的SEO的愚蠢的词。作为启动点,请尝试以下操作:
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 = 20; //number of chars
$desired_words = 5; //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;
}
请注意,这是完全未经测试的,我只是写了它,所以它可能有一些怪癖,但这是一个很好的起点。