Wordpress - Force post slug to be auto generated from title on save

The easiest workaround could be:

function myplugin_update_slug( $data, $postarr ) {
    if ( ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = sanitize_title( $data['post_title'] );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );

Also, run the slug from sanitize_title_with_dashes() through wp_unique_post_slug() to ensure that it's unique. It will automatically append '-2', '-3' etc. if it's needed.


Instead of replacing spaces you should use the build in function sanitize_title() which will take care of the replacing for you.

Like this:

sanitize_title( $post_title, $post->ID );

Also, you should use a unique slug. Which you can get with the function wp_unique_post_slug()

So putting it all together a solution might be:

function myplugin_update_slug( $data, $postarr ) {
    if ( ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'myplugin_update_slug', 99, 2 );