以下是我为实现这一点所做的:
function slug_save_post_callback( $post_ID, $post, $update ) {
// allow \'publish\', \'draft\', \'future\'
if ($post->post_type != \'post\' || $post->post_status == \'auto-draft\')
return;
// only change slug when the post is created (both dates are equal)
if ($post->post_date_gmt != $post->post_modified_gmt)
return;
// use title, since $post->post_name might have unique numbers added
$new_slug = sanitize_title( $post->post_title, $post_ID );
$subtitle = sanitize_title( get_field( \'subtitle\', $post_ID ), \'\' );
if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
return; // No subtitle or already in slug
$new_slug .= \'-\' . $subtitle;
if ($new_slug == $post->post_name)
return; // already set
// unhook this function to prevent infinite looping
remove_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
// update the post slug (WP handles unique post slug)
wp_update_post( array(
\'ID\' => $post_ID,
\'post_name\' => $new_slug
));
// re-hook this function
add_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
}
add_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
它生成并更新
slug
. 之前由WP生成的slug不能重用,因为如果标题/slug已经在另一篇文章中使用,那么它可以具有唯一的编号。所以,我清理了标题。然后
wp_update_post
确保新的slug没有重复项
wp_unique_post_slug
.
我能找到的唯一方法是在发布时进行此操作,即比较创建时间和修改时间。只有在创建帖子时,它们才相等。这个$update
参数无效,因为true
用于发布。