Set a randomised & unique slug for posts in WordPress

by Dan
Last updated: September 26th, 2020

When working on The Luminous I needed a way to automatically generate an entirely random and unique slug for posts of a custom post type.

The Luminous is a fine-art stock-photography website and each of the images within their image gallery is actually a post within a custom post type called “photos”. The images didn’t require a title to be displayed and couldn’t be shared outside of the membership paywall, so using SEO friendly url’s wasn’t a requirement.

What we did need though, was a way for members to share links to images with their teammates and other members on the platform. So I created a function to set the url as an md5 hash of the time that the post was published.

// Set a random & unique slug for Photos Custom Post Type add_filter( 'wp_unique_post_slug', 'custom_unique_post_slug', 10, 4 ); function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) { if ( 'photos' == $post_type ) { // change to match your post type $post = get_post($post_ID); if ( empty($post->post_name) || $slug != $post->post_name ) { $slug = md5( time() ); } } return $slug; }

we think you'll probably like these too