0

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.com/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.com/events/staff-meeting/
http://example.com/events/staff-meeting-2/
http://example.com/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".

  • 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 Feb 4 at 22:58
1

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;
}
  • This works when editing the post with the Classic Editor. When I edit it with Gutenberg, the post slug does not include the custom field. – Chris Wathen Feb 5 at 5:33
  • I have also tested it in Guttenberg and it does work. – hamdirizal Feb 5 at 9:00
  • It looks like with Gutenberg, the slug is created while you are typing in the title. I'm able to get the prefix added when I publish the post, then update it. So it's firing the function on the second save of the post. Here is a video showing both Gutenberg and the Classic Editor: screencast-o-matic.com/watch/cqnh2o35vY – Chris Wathen Feb 5 at 14:21

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.