Snippets / PHP
Generate unique SLUG for custom post type with no plugin
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.
// 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,
] );
}
Discussion 1
Ask a question or share how you used this.
Hi There is a mistake in your code. Your PHP code changes were not applied due to an error on line 56 of file wp-content/themes/voxel-child/functions.php. Please fix and try saving again. syntax error, unexpected identifier "wp_update_post"
Hello, there's no error from our end, please ensure there's no duplicate "<?php" text causing this error on your code.
Hi, thanks for your answer, and I checked the Child theme; there are no error codes. Could you please check the screenshot by link below. https://ibb.co/R3yMLsy