Home > front end >  How to update a field while creating a new post with ACF form
How to update a field while creating a new post with ACF form

Time:11-25

I'm using an ACF Form in the front-end of a WordPress website. The ACF form in 'Post A' creates a new post 'Post B'. I am trying to create a function that will update an ACF field in Post A (I will then use this to remove the form from Post A so that it can only be submitted once). I have been trying to use an acf/save_post action to update the field but this seems to only effect Post B and not Post A. Here is my code:

<?php 
add_action('acf/save_post', 'update_post_status', 20);

function update_post_status( $post_id ) {

    if( get_post_type($post_id) !== 'mypost' ) {
        return;
    }
  
    update_field('form_submitted', 'yes');
  
}
?>

CodePudding user response:

I think that you use the incorrect hook for this task

acf-save_post


Fires when saving the submitted $_POST data.

You can use 'save_post'

Save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST.

For example

add_action( 'save_post', 'my_save_post_function', 10, 3 );

function my_save_post_function( $post_ID, $post, $update ) {
    if( get_post_type($post_ID) !== 'mypost' ) {
        return;
    }
  
    update_field('form_submitted', 'yes', $post_ID);
}

CodePudding user response:

Ive had success with using acf/validate_save_post rather than acf/save_post as this fires before the new post is created so the function still refers to the original post.

  • Related