Support

Account

Home Forums Front-end Issues ACF Repeater Filed in add_post_meta Reply To: ACF Repeater Filed in add_post_meta

  • I’ll try to answer this, it may be confusing. Storing data in the database, especially if you want to interact with it using acf functions is more difficult using standard functions.

    from the WP Codex: add_post_meta($post_id, $meta_key, $meta_value, $unique);

    Lets take a simple text field that has a field name of “text_field” and a field key of “field_5443d4e2dd4e4”. The first thing is that ACF stores 2 values for each field.

    To insert this so that ACF interacts with it properly you need:

    
    add_post_meta($post_id, 'text_field', 'my value', true);
    add_post_meta($post_id, '_text_field', 'field_5443d4e2dd4e4', true);
    

    The second value is how ACF finds your field. It is simply your field name prefixed with an underscore and the field value is the ACF field key.

    Note that the above is for adding a new post. When updating a post you would need to use update_post_meta(), and you’d need to make sure you preserve the uniqueness of the meta value for the $post_id.

    now lets look at a repeater field with a single sub field that has some values in the sub field.

    ‘Repeater:
    ‘field_name’ => ‘repeater’
    ‘field_key’ => ‘field_5443d4e2dd4e4’

    Sub Field:
    ‘field_name’ => ‘sub_field’
    ‘field_key’ => ‘field_5443d4e2dd4e5’`

    Here is an array with the sub field values

    
    $values = array('value 1', 'value 2', 'value 3');
    

    Now the code to insert the repeater values:

    
    $repeater_field = 'repeater';
    $repeater_key = 'field_5443d4e2dd4e4';
    $sub_field = 'sub_field';
    $sub_field_key = 'field_5443d4e2dd4e5';
    
    $count = count($values);
    if ($count) {
      // the db value stored in the db for a repeater is
      // the number if rows in the repeater
      add_post_meta($post_id, $repeater_field, $count, true);
      add_post_meta($post_id, '_'.$repeater_field, $repeater_key, true);
      for ($i=0; $i<$count; $i++) {
        // the actual field name in the DB is a concatenation of
        // the repeater field name, the index of the current row
        // and the sub field name, with underscores added
        $sub_field_name = $repeater_field.'_'.$i.'_'.$sub_field;
        add_post_meta($post_id, $sub_field_name, $values[$i], false);
        add_post_meta($post_id, '_'.$sub_field_name, $sub_field_key, false);
      }
    }
    

    Hope that helps

    ~JH