Hello,
Thanks for the feedback!
In fact, you should be careful when using the acf/save_post
hook, as this action will be executed anywhere in the admin when updating a Post/User/Term/Options Page etc… and on front-end forms too (using the native ACF Form or ACFE Form).
Since it is executed on different objects such as Post/User/Term/Options Page, the $post_id
passed by ACF will reflect that object (See documentation). Example:
$post_id = 123; // on a Post Type page
$post_id = 'user_12'; // on a User page
$post_id = 'term_45'; // on a Term page
$post_id = 'my-options'; // on an Options Page
In the case of the ACFE Form, the $post_id = false
, and since you use wp_update_post()
in that hook and assign with ID = $post_id
(ID = false
), WordPress will try to retrieve the current post (the “Form” page on the front-end), and generate a new page from it.
Based on those information, when using acf/save_post
I recommend to always check and validate the $post_id
to make sure it targets the Post Type/User/Term/Options Page of your choice.
Note that you can also use is_admin()
as a condition if you want to make sure your code is only executed in the admin if needed. Usage example:
add_action('acf/save_post', 'my_acf_save_post', 20);
function my_acf_save_post($post_id){
// stop if: on front-end OR post_id is not numeric OR post_type is not "page"
if(!is_admin() || !is_numeric($post_id) || get_post_type($post_id) !== 'page'){
return;
}
// you're now sure you're currently updating a post type "page" in the admin only
// wp_update_post(...)
}
You could also write it like that, if that’s more clear:
add_action('acf/save_post', 'my_acf_save_post', 20);
function my_acf_save_post($post_id){
// stop if front-end
if(!is_admin()){
return;
}
// stop if post_id is not numeric (user, term, options page etc...)
if(!is_numeric($post_id)){
return;
}
// stop if post_type is not "page"
if(get_post_type($post_id) !== 'page'){
return;
}
// you're now sure you're currently updating a post type "page" in the admin only
// wp_update_post(...)
}
PS: Thanks for the words of encouragement ??
Hope it helps!
Have a nice day!
Regards.