Skip to content

Snippets / PHP

PHP

Generate unique SLUG for custom post type with no plugin

O online.manage.nc · 274 views · Updated 1 year ago
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.
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 · 24 lines

Discussion 1

Ask a question or share how you used this.

Log in to join the discussion.
artinkupar 1 year ago

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"

online.manage.nc 1 year ago

Hello, there's no error from our end, please ensure there's no duplicate "<?php" text causing this error on your code.

artinkupar 1 year ago

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

artinkupar 1 year ago

Hi, any comment?

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.