Skip to content

Instantly share code, notes, and snippets.

@jamesmorrison
Last active June 7, 2021 04:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmorrison/953590ad44db509885e37114dbc7c110 to your computer and use it in GitHub Desktop.
Save jamesmorrison/953590ad44db509885e37114dbc7c110 to your computer and use it in GitHub Desktop.
Replace the default WP post slug with a random one in the format is "XXXX-XXXX-XXXX-XXXX"
<?php
/**
*
* Filter post slug
* This needs saving as post meta to use that value rather than regenerate a new one
*
**/
add_filter( 'wp_unique_post_slug', function( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
if ( ! in_array( $post_type, array( 'post' ) ) ) {
return $slug;
}
if ( ! $slug = esc_attr( get_post_meta( $post_ID, '_slug', true ) ) ) {
// The chance of this returning the same URL twice is 1 in 20,000,000,000. Unlikely, but possible..
$slug = esc_attr( wordwrap( strtolower( wp_generate_password( 16, false, false ) ), 4 , '-' , true ) );
update_post_meta( $post_ID, '_slug', $slug );
}
return $slug;
}, 10, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment