Automatically update slug with latest title within custom post type

I’m trying to update the slug for all the post within a specific custom post type, let’s say “music”.

Here is the code:

/* Update slug with the latest post title */
function auto_update_post_slug($postId, $after, $before) {
if ($after->post_title != $before->post_title) {
$after->post_name = ”;
wp_update_post($after);
}
}

/* Check if custom post type music, if true, add action to auto update slug */
function enqueue_music_features( $hook_suffix ){
$my_custom_post_type = ‘music’;

if( in_array($hook_suffix, array(‘post.php’, ‘post-new.php’) ) ){
$screen = get_current_screen();

if( is_object( $screen ) && $my_custom_post_type == $screen->post_type ){

/* add custom post type music features */
add_action(‘post_updated’, ‘auto_update_post_slug’, 10, 3);

echo “<script type=’text/javascript’>alert(‘This has been called’);</script>”;

}
}
}
add_action( ‘admin_enqueue_scripts’, ‘enqueue_music_features’);

What I do know that the enqueue_music_features works, and that auto_update_post_slug works by itself if you put it outside enqueue_music_features. I also tried putting the entire auto_update_post_slug inside the hook, that didn’t work either.

Read more here:: Automatically update slug with latest title within custom post type

Leave a Reply

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