Generate unique SLUG for custom post type with no plugin

Description/Instructions

This PHP code lets you target a CPT by its key, and replace its SLUG (which usually displays the post title) with a unique SLUG composed of the date and time of publication, and its ID.

This works as soon as an event is published, but can also be applied when it is modified (if you already have existing posts).

The SLUG will not change once the post has been published, as it remains on a fixed basis:

– Its publication date
– Its ID

This makes it possible to generate a unique SLUG with an almost “random” component thanks to the publication date.

Instructions

  • Add this code to the function.php of your child theme
  • Replace the YOUR_KEY by the key of your CPT
  • Save

// GENERATE UNIQUE SLUG CPT
add_action( 'voxel/app-events/post-types/YOUR_KEY/post:submitted', '_set_custom_post_slug_YOUR_KEY' );
add_action( 'voxel/app-events/post-types/YOUR_KEY/post:updated', '_set_custom_post_slug_YOUR_KEY' );

function _set_custom_post_slug_YOUR_KEY( $event ) {
// Get post ID
$post_id = $event->post->get_id();

// Get the date and time of the publication
$post_date = get_post_field( 'post_date', $post_id );

// Extract month (2 digits) and time (HHMM)
$month = date( 'm', strtotime( $post_date ) );
$time = date( 'Hi', strtotime( $post_date ) );

// Create a slug with the format month (2 digits), time (4 digits) and post ID
$post_slug = sprintf( '%s%s%s', $month, $post_id, $time );  // Reorder if needed

// Update post with new slug
wp_update_post( [
'ID' => $post_id,
'post_name' => $post_slug, 
] );
}

  • PHP
Copy Code

Let's Chat About this Snippet