I'd like to change the slug that is automatically generated when creating a post.

enter image description here

I'd like to add a meta before, making a thing like [meta]-test-slug-2

I guess there's a hook on when WP automatically creates a slug, and if I could find it, I could inject that meta before the title when creating the slug.

So is there a hook that exists? If so, how can I use it?


I think you should be able to do this using the wp_unique_post_slug filter (which is applied in the function of the same name):

add_filter("wp_unique_post_slug", function($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) {
    if($meta = get_post_meta($post_ID, "my-meta", true)) {
        $slug = $meta . '-' . $slug;
    return $slug;
}, 10, 6);

As this is applied at the end of that function and I believe WP expects and relies upon that slug to be unique, you will have to make sure that it is. I believe that it will be generated (and saved) as the post is published, so you'll have to have your meta values ready by then.

  • I dont know what I'm doing wrong. I'm trying to add the date before as a test, and it doesnt work add_filter("wp_unique_post_slug", function($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug) { /*if($meta = get_post_meta($post_ID, "my-meta", true)) { $slug = $meta . '-' . $slug; }*/ $slug = date('Y-m-d').'-'.$slug; return $slug; }, 10, 6);
    – Fredy31
    Nov 10 '17 at 15:44
  • What's (not) happening? Adding the date that way works fine for me. Is the function not called at all, or is it not saved to the DB (wp_posts => post_name)?
    – janh
    Nov 10 '17 at 15:55
  • Threw a priority of 9999, it did pass. My problem was priority.
    – Fredy31
    Nov 10 '17 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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