WordPress 限制 post slug 长度

WordPress的url含有关键词对seo有利,但是如果太长也不好,不利于收录,特别在自动生成slug的情况下,可以通过以下的代码对其限制:

把以下代码放到function.php中即可。

/**
* limit slug length 100 characters.
*/
add_filter( 'wp_unique_post_slug', 'custom_unique_post_slug', 10, 4 );
function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type) {
if ( 'post' == $post_type ) {
$post = get_post($post_ID);
if ( empty($post->post_name) || $slug != $post->post_name ) {
if(strlen($slug)>100){
if(substr($slug,99,100)=='-'){
$slug = substr($slug, 0,99);
}else{
$slug = substr($slug, 0,100);
}
//$slug = wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, '0');
global $wpdb;
$sql = "SELECT count(ID) FROM $wpdb->posts WHERE post_name like '".$slug."%' AND ID!=".$post_ID;
$num = $wpdb->get_var($sql);
if($num){
$slug = $slug.'-'.($num+1);
}
}
}
}
return $slug;
}