Support

Account

Home Forums General Issues Matching $_POST key and ACF field name

Solved

Matching $_POST key and ACF field name

  • Hi!

    I was just wondering if anyone knew a possible way to match the input name submitted through $_POST with an acf field name.

    Here’s the scenario:

    I’m creating posts in a CPT from a front end form via wp_insert_posts(). All of the fields in the frontend form need to be updated into individual acf fields.

    All of the field names match the acf field names.

    For example

    
    <input type="text" name="user_name" value="" placeholder="User Name" />
    <input type="text" name="userquestion" value="" placeholder="User Question" />
    

    ACF Fields

    There’s around 40 fields and will take forever to do an update_field() for every acf field.

    Is there a simple way to loop of the $_POST and match it with the field names?

  • You have the field names and are looking for the field keys. It would be possible to do this if those fields already exist in the database for the post using get_field_object($field_name, $post_id) However, since you are creating post then these fields do not exist and there isn’t any way to match them up.

    You have to know the field keys.

    You could build an array of field name => field key pairs

    
    $fields = array(
      'field_name_1' => 'field_key_1',
      'field_name_2' => 'field_key_2',
      // etc...
    );
    foreach ($_POST as $field_name => $value) {
      update_field($fields[$field_name], $value, $post_id);
    }
    
  • You are a wizard!

    — Edit —
    Here’s a working example for anyone in the future:

    
    $acf_fields = array(
        'user_name'          => 'field_5ca80efacb9fb',
        'userQuestion'       => 'field_5ca80f19cb9fc',
        'userQuestionAnswer' => 'field_5ca80f2acb9fd',
    );
    
    $new_post = array(
        'post_title'    => $_POST['user_name'],
        'post_status'   => 'publish',          
        'post_type'     =>  'entries' 
    );
    
    $post_id = wp_insert_post($new_post);
    
    foreach ( $_POST as $field_name => $value ) {
        
        if( isset( $_POST[$field_name] ) ) {
            update_field( $acf_fields[$field_name], $value, $post_id );
        }
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Matching $_POST key and ACF field name’ is closed to new replies.