保存帖子url时,此代码将更新帖子url:
function wpse_288020_replace_url( $post_id ) {
$post_type = get_post_type( $post_id );
if( $post_type === \'your_post_type\' ) {
$title = get_the_title( $post_id );
$title = sanitize_title( $title );
$post = array(
\'ID\' => $post_id,
\'post_name\' => sprintf(\'%s-%s\', $title, $post_id),
);
remove_action( \'save_post\', \'wpse_288020_replace_url\' ); // Remove action to prevent loop
wp_update_post( $post );
add_action( \'save_post\', \'wpse_288020_replace_url\' );
}
}
add_action( \'save_post\', \'wpse_288020_replace_url\' );
此代码将对您的所有帖子URL进行大规模更新:
function wpse_288020_batch_replace_url() {
// Get all posts
$query = new WP_Query(array(
\'post_type\' => \'post\',
\'posts_per_page\' => -1,
));
$posts = $query->get_posts();
foreach ($posts as $post) {
// Get permalink
$title = sanitize_title($post->post_title);
// Prepare arguments
$args = array(
\'ID\' => $post->ID,
\'post_name\' => sprintf(\'%s-%s\', $title, $post->ID),
);
// Update post
wp_update_post( $args );
}
}
add_action(\'init\', \'wpse_288020_batch_replace_url\');
如果有许多帖子,请通过添加
WP_POST_REVISIONS
常数至
wp-config.php
. 它将加快脚本速度并减少对内存使用的需求。
define( \'WP_POST_REVISIONS\', false );