POST的唯一slug是由wp_unique_post_slug()
. 查看返回的段塞的过滤源wp_unique_post_slug
. 所以我们可以用我们自己的替换这个生成的slug。
您将在源代码中注意到,附件需要在所有类型中都具有唯一的slug,因此我们将只使用其中的代码。
您给出的示例似乎是非层次式的-并且不清楚您是否希望slug对于层次式帖子类型是唯一的(默认情况下,它只需要在树中是唯一的)-因此在下面的示例中,我忽略了层次式帖子类型。
add_filter(\'wp_unique_post_slug\', \'wpse72553_cross_type_unique_slugs\',10,5);
function wpse72553_cross_type_unique_slugs( $slug, $post_ID, $post_status, $post_type, $post_parent ){
global $wpdb, $wp_rewrite;
//Don\'t touch hierarchical post types
$hierarchical_post_types = get_post_types( array(\'hierarchical\' => true) );
if( in_array( $post_type, $hierarchical_post_types ) )
return $slug;
if( \'attachment\' == $post_type ){
//These will be unique anyway
return $slug;
}
$feeds = $wp_rewrite->feeds;
if ( ! is_array( $feeds ) )
$feeds = array();
//Lets make sure the slug is really unique:
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
if ( $post_name_check || in_array( $slug, $feeds) ) {
$suffix = 2;
do {
$alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
$post_name_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_post_name, $post_ID ) );
$suffix++;
} while ( $post_name_check );
$slug = $alt_post_name;
}
return $slug;
}