Support

Account

Home Forums Front-end Issues Use update_field() to fill in a field automatically

Helping

Use update_field() to fill in a field automatically

  • Hi there,

    I want to use update_field() function to fill in a field value automatically. However, the post saved but update_field() function doesn’t work.

    here is my code in function.php:

    add_filter('acf/pre_save_post' , 'do_pre_save_post' );
    function do_pre_save_post( $post_id ) {
    	
    if( $post_id != 'new' ) {
        return $post_id;
    }
    
    if (isset($_POST['my_pt'])) {
    	$new_post_type = "receipts";
            $title = wp_strip_all_tags($_POST['acf']['field_570f5acd84b60']);
    	$product = $_POST['product'];
    	
    	$post = array(
            	'post_type'     => $new_post_type, 
            	'post_status'   => 'publish', 
            	'post_title'    => $title, 
        );
    	
    	$post_id = wp_insert_post( $post );
    	
    	update_field( "field_570f5b3f22fad", $product, $post_id );
    }
    
    return $post_id;
    
    }

    and here is the acf_form code:

    $new_post = array(
    			'post_id'            => 'new',
    			'field_groups'       => array(68,72),
    			'form'               => true,
    			'return'             => '%post_url%',
    			'html_before_fields' => '',
    			'html_after_fields'  => '<div><input type="hidden" name="my_pt" value="receipts"><input type="hidden" name="product" value="'.$product_no.'"></div>',
    			'submit_value'       => 'Submit',
    			'updated_message'    => 'Saved'
    		);
    		acf_form( $new_post );

    Thank you for help!!!

  • Hi @joshualeong

    You don’t need to use the wp_insert_post() function anymore with acf_form(). You can set the post type and status by passing the new_post arguments. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/using-acf_form-to-create-a-new-post/. If you want to change the title, I suggest you use the acf/save_post and wp_update_post() instead.

    I hope this helps.

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

The topic ‘Use update_field() to fill in a field automatically’ is closed to new replies.