4

My Situation

I'm using Advanced Custom Fields Pro to store metadata for a post in wordpress.

My posts are created dynamically (not through the administrative interface), which means that I explicitly need to populate metadata using field keys, not field names. One of my fields is a repeater field with a single text area and another is a standard text area.

My Code

The following code is what I call (once per post). The post is created using wp_insert_post() earlier.

  // Populate "Name"
  update_field('field_566e360961c2f', 'John Doe', $wp_identifier);

  // Populate "Sponsors"
  foreach($sponsors as $sponsor) {

      // Define "Sponsor Name"
      $new_sponsor = array(
        'field_566e32fb943a5' => 'Beats and Corn Companye'
      );

      add_row('field_566e32bd943a4', $new_sponsor, $wp_identifier);
  }

The result of this is that standard text fields populate, and a single "sponsor" repeater item is created, but the value of the sponsor name is blank.

The relevant wp_postmeta data that is generated looks like this:

|   18226 |      71 | name                    | John Doe
|   19234 |      71 | sponsors                | 1                                                            |
|   19235 |      71 | _0_field_566e32fb943a5  | Beats and Corn Company                                                                             |

My Question

What am I doing wrong? Looking at the documentation for add_row() this appears to be the correct approach. Is it possible that repeater fields have a different way of notating keys that I'm not aware of?

1 Answer 1

9

This isn't made incredibly clear in the documentation today, but it turns out add_row only works if an existing row had already been saved. When trying to populate a repeater field for the very first time you have to use update_field instead and pass an array of value arrays.

The corrected code:

  // Populate "Name"
  update_field('field_566e360961c2f', 'John Doe', $wp_identifier);

  // Populate "Sponsors"
  $new_sponsors = array();
  foreach($sponsors as $sponsor) {

      // Define "Sponsor Name"
      $new_sponsor = array(
        'field_566e32fb943a5' => 'Beats and Corn Companye'
      );
      $new_sponsors[] = $new_sponsor;
  }

  update_field('field_566e32bd943a4', $new_sponsors, $wp_identifier);
3
  • 1
    Note. To get field_id in Custom Fields > Fields Group > Field Keys check "Field Keys" Oct 13, 2016 at 17:51
  • Adding on to what @KārlisMillers said, the "Field Keys" option can be checked in the Screen Options drop down. Feb 15, 2021 at 0:32
  • 1
    I think add_row works now, even if there's no existing row. Worked for me after deleting all existing rows and then trying it. Feb 15, 2021 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.