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 comments
Comments are closed.
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 usingadd_action
.Hence, your case would have to look something like this:
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 thesave_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:
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).