Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add_row in ACF Pro isn't saving repeater values

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?

like image 573
slifty Avatar asked Jan 07 '23 23:01

slifty


1 Answers

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);
like image 92
slifty Avatar answered Jan 15 '23 13:01

slifty