Support

Account

Home Forums Backend Issues (wp-admin) save_post always fired twice when ACF fields present

Helping

save_post always fired twice when ACF fields present

  • I have a CPT with ACF fields.

    I’m trying to create a custom PHP snippet to send an email to the admin on a date determined by an ACF dat field.

    I’m checking the data initially when the post is first posted or updated.

    However, the function is triggered twice, once with the ACF date data and once without.

    It seems, from research, that when saved, WP triggers a save and ACF also triggers a save (with the ACF data)

    I thought about using the acf/save_post but if I don’t amend and ACF data, it doesn’t trigger.

    I need this to trigger only once, so when a post is saved, how can I trigger a function that includes the ACF data (even if ACF fields not modified)?

    Here’s my PHP snippet:

    function webroom_send_mail_on_new_post( $post_id, $post  ) {
    
    	if ($post->post_status !== 'auto-draft'){
    	
    			$to = '[email protected]';
    			$updateDate = get_field(document_review_date_reminder_trigger);
    			$post_title = $post->post_title;
    			$postStatus = $post->post_status;
    			$subject = 'New Post Published ' . $post_title;
    			$message = 'Hi, new post is published on your website: ' . $post_title . ' To be updated: ' . $updateDate . ' post status: ' . $postStatus;
                wp_mail($to, $subject, $message);
    	}
    }
    add_action( 'save_post_document', 'webroom_send_mail_on_new_post');
  • Your problem is that the action hook that you are using happens before the hook used by acf

    
    /** This action is documented in wp-includes/post.php */
    do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
    
    /** This action is documented in wp-includes/post.php */
    do_action( 'save_post', $post->ID, $post, true );
    

    ACF is triggered on the save_post hook with a priority of 10. This means that when your action runs ACF has not yet saved any values. The first time your action runs there are no values and thereafter each times that your action runs it is getting the old value instead of the new value.

    You have 2 choices.

    1) Get the value from the submitted value in $_POST[‘acf’] see discussion about applied before save for acf/save_post https://www.advancedcustomfields.com/resources/acf-save_post/

    2) You could use the save_post hook with a priority > 10.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.