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".

  • 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 1


You can filter the slug creation on wp_unique_post_slug hook.

//Register the filter

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);
            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. Commented Feb 5, 2019 at 5:33
  • I have also tested it in Guttenberg and it does work.
    – hamdirizal
    Commented Feb 5, 2019 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 Commented Feb 5, 2019 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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