I need to retrieve an ACF field within the post, and change the slug(permalink) of the post before saving it to database. What is the approach to achieve that? I need the slug to be changed every create/edit post operations.

2 Answers 2


The following is to be taken more as a proof of concept rather than a copy/paste-ready solution.
That being said, this is how you'd go about it:

The save_post action runs whenever a post is updated or created. You can hook a callback function to it using add_action.

Hence, your case would have to look something like this:

// initial hook
add_action( 'save_post', 'wpse105926_save_post_callback' );

function wpse105926_save_post_callback( $post_id ) {

    // verify post is not a revision
    if ( ! wp_is_post_revision( $post_id ) ) {

        // unhook this function to prevent infinite looping
        remove_action( 'save_post', 'wpse105926_save_post_callback' );

        // update the post slug
        wp_update_post( array(
            'ID' => $post_id,
            'post_name' => 'some-new-slug' // do your thing here

        // re-hook this function
        add_action( 'save_post', 'wpse105926_save_post_callback' );


What might be a bit confusing in the above is the un- and rehooking of the function from within it. This is required, since we call wp_update_post to update the slug, which in turn will trigger the save_post action to run again.

As an aside, if you want WP to automatically generate the new slug based on the post title, simply pass an empty string:

wp_update_post( array(
    'ID' => $post_id,
    'post_name' => '' // slug will be generated by WP based on post title
  • thank you for the concept, it helped me to understand the process better
    – Vit Kos
    Commented Jul 10, 2013 at 10:31
  • The question refers to ACF, specifically to "retrieve" the field (value) and your concept works in php and misses EXACTLY what you commented as "do your thing here". Can you throw a proof of concept for the retrieval as well? (remember the #postname field is not even there until the button "edit" (permalink) is clicked. Same with the invisible field #new-post-slug)
    – sergio
    Commented Jul 9, 2015 at 6:54
  • 1
    Could I not do this also by using wp_insert_post_data filter, which runs after sanitazing, right before save? Whats the biggest benefit to this method. Commented Sep 3, 2017 at 9:22

I needed the same except that only for post creation.

I implemented the solution here (this one is copy/paste-ready 😉).

Just remove the line which checks that both dates are equal, and it will update the slug for edit operations too. However, I do not recommend that since it will change the URL of the post and this is not good for SEO, among other things like broken links (404).

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.