Rewriting post slug before post save

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
));

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x