How to automatically update permalink when post is updated?

It is sometimes useful to automatically update the permalink of a post when the title is changed. This function, which you can copy into your plugin or function file, will update the permalink each time post type ‘planes’ are updated.

In this case, we use title and post-id to create the slug:

<?php
// update permalink when post type planes is updated
add_action( 'save_post_planes', 'wpster_planes_custom_slug', 10, 2 );
function wpster_planes_custom_slug( $post_id, $post ) {      
	remove_action( 'save_post_planes', 'wpster_planes_custom_slug' );
	$new_slug = sanitize_title( $post->post_title ).'-'.$post_id; 
	wp_update_post( array(
		'ID' => $post_id,
		'post_name' => $new_slug
	));
	clean_post_cache( $post_id );
	add_action( 'save_post_planes', 'wpster_planes_custom_slug', 10, 2 );
}
?>

Submit a Comment

Your email address will not be published. Required fields are marked *