I have a simple custom post type set up for Events. I'm using Carbon Fields to add a Start Date field which I would like to include in the post_name. For example:
/
I'd like to have the post_name created when they save the event, adding the custom field "cw_event_start_date" to the post_name to prevent the URLs from looking like this:
/
/
/
We won't have to worry about duplicate events on the same date, and if they did it should create the post_name as "20180401-staff-meeting-2".
I have a simple custom post type set up for Events. I'm using Carbon Fields to add a Start Date field which I would like to include in the post_name. For example:
http://example/events/20190401-staff-meeting/
I'd like to have the post_name created when they save the event, adding the custom field "cw_event_start_date" to the post_name to prevent the URLs from looking like this:
http://example/events/staff-meeting/
http://example/events/staff-meeting-2/
http://example/events/staff-meeting-3/
We won't have to worry about duplicate events on the same date, and if they did it should create the post_name as "20180401-staff-meeting-2".
You can filter the slug creation on wp_unique_post_slug
hook.
//Register the filter
add_filter('wp_unique_post_slug','prefix_the_slug',10,6);
function prefix_the_slug($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug){
//Get value from the custom field
$prefix = get_post_meta($post_ID,'cw_event_start_date',true);
//Only prefix certain post type and if prefix field existed
if($post_type==='post' && $prefix && !empty($prefix)){
//Prefix only if it is not already prefixed
preg_match ('/^\d\d\d\d\d\d/', $slug, $matches, PREG_OFFSET_CAPTURE);
if(empty($matches)){
return $prefix.'-'.$slug;
}
}
return $slug;
}