Random WordPress post slug
I wanted WordPress to generate random post slugs when I don’t enter a post title. I asked https://mastodon.social/@janboddez how he did it, and he has written a blog post about it in 2019.
I’ve changed the code a bit for my need. If you want it, just paste this in your functions.php
add_filter( 'wp_insert_post_data', function( $data, $postarr ) {
if ( ! empty( $postarr['ID'] ) ) {
// Not a new post.
return $data;
}
if ( ! empty( $postarr['meta_input']['mf2_post-of'][0] ) ) {
$data['post_type'] = 'post';
}
if ( in_array( $data['post_type'], array( 'post' ), true ) ) {
global $wpdb;
do {
$slug = bin2hex( openssl_random_pseudo_bytes( 3 ) );
$result = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s LIMIT 1", $slug ) );
} while ( $result );
$data['post_name'] = $slug;
}
return $data;
}, 10, 2 );