How can I automatically set a post slug based on the post title during post publish?
-
22-10-2019 - |
Question
When you create a post in WP, if you don't specify a title rapidly, WP generates a default slug on autosave, based on the post ID. Then, when you add the title later, unless you modify the slug by editing it, it remains the same (based on post ID)
What I'm trying to do is add an action on post publish, that generates and saves the post slug, based on the post title.
Solution
As long as haven’t touched the slug WordPress will generate a new one after you entered a title.
Update
To change other peoples slugs use a filter (not tested!):
add_filter( 'wp_insert_post_data', 'prevent_numeric_slugs', 10, 1 );
function prevent_numeric_slugs( $post_data )
{
if ( ! isset ( $post_data['post_title'] )
or ! is_numeric( $post_data['post_name'] )
)
{ // exit early
return $post_data;
}
// post_name is the slug
$post_data['post_name'] = sanitize_title( $post_data['post_title'] );
return $post_data;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange