add_row in ACF Pro isn't saving repeater values

本小妞迷上赌 提交于 2019-12-11 00:18:38

问题


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:


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);


来源:https://stackoverflow.com/questions/34305000/add-row-in-acf-pro-isnt-saving-repeater-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!