这可能会有一些怪癖,但实际上它会满足您的需求。请注意,它设置为仅适用于帖子(不适用于页面或自定义帖子类型)。
我们所做的就是使用wp_unique_post_slug
过滤器,在WordPress生成自己独特的slug后运行,并根据所有_wp_old_slug
元值。您将在我的自定义查询中看到,我仍然在主posts表中对照slug进行检查-如果没有它,我们可能会“重置”后缀计数,并与现有post发生冲突。
function wpse_183975_unique_post_slug( $slug, $post_id, $post_status, $post_type ) {
if ( $post_status === \'publish\' && $post_type === \'post\' ) {
global $wpdb;
if ( preg_match( \'/-([0-9]+)$/\', $slug, $match ) ) { // Already has a number suffix
$slug_base = substr( $slug, 0, -strlen( $match[0] ) ); // Strip suffix from slug
$i = ( int ) $match[1];
} else { // No suffix, start at 1
$slug_base = $slug;
$i = 1;
}
while ( // For as long as there is an existing slug, increment the suffix
$wpdb->get_var(
$wpdb->prepare(
"SELECT m.post_id FROM $wpdb->postmeta AS m INNER JOIN $wpdb->posts AS p ON m.post_id = p.ID " .
"WHERE " .
"p.ID != %d AND " .
"p.post_type = \'post\' AND " .
"( p.post_status = \'publish\' AND p.post_name = %s ) OR " .
"( m.meta_key = \'_wp_old_slug\' AND m.meta_value = %s ) " .
"LIMIT 1",
$post_id,
$slug,
$slug
)
)
) {
$slug = "$slug_base-" . ++$i;
}
}
return $slug;
}
add_filter( \'wp_unique_post_slug\', \'wpse_183975_unique_post_slug\', 10, 4 );