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".
Share Improve this question asked Feb 4, 2019 at 22:43 Chris WathenChris Wathen 31 silver badge2 bronze badges 1- What did you try already, can we see some code so we can try to help you out? Because this forum would not exists if we just put requests here, so please show some own input, thank you. – Charles Commented Feb 4, 2019 at 22:58
1 Answer
Reset to default 1You 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;
}