I have a custom post type Event with a variable number of Tickets (each has name and amount), for which I wanted to use the repeater field. In my case users are the ones adding events into the system through the custom front-end.
In order to get this working with ACF I needed the repeater's field key (looks like "field_512d3adcdb59a"). The only solution to acquire it presented in the doc is to go through a manual process outlined in "Finding the field key" on this page. This wasn't an option for me. Here's the code which gets it, given the group title and the repeater field name. You can either hard-code it or provide as option fields in your plugin (which I did). Below is the hard-coded version, for simplicity.
You can adapt it to get any field's key, not just repeaters.
Ideally there would be a function in the ACF's API to get the field key given the field name. Just saying! :)
In order to get this working with ACF I needed the repeater's field key (looks like "field_512d3adcdb59a"). The only solution to acquire it presented in the doc is to go through a manual process outlined in "Finding the field key" on this page. This wasn't an option for me. Here's the code which gets it, given the group title and the repeater field name. You can either hard-code it or provide as option fields in your plugin (which I did). Below is the hard-coded version, for simplicity.
$acf_group_title = 'your-group-title'; /* no capitals, dashes instead of spaces, appears directly under 'Edit Field Group' */
$acf_field_title = 'your_field_name'; /* Field Name of your repeater (not the label!) */
$acf_field_key = '';
$data_to_insert = array(array("sub_field_1" => "Foo1", "sub_field_2" => "Bar1"), array("sub_field_1" => "Foo2", "sub_field_2" => "Bar2"));
$acf_args = array(
'post_type' => 'acf',
'posts_per_page' => 1,
'post_status' => 'publish',
'acf_field' => $acf_group_title
);
$acf_query = new wp_query( $acf_args ); // get the post which ACF uses to keep all the field group settings
if ( $acf_query->have_posts() && isset($acf_query->posts[0]) ) {
$meta_values = get_post_meta($acf_query->posts[0]->ID);
foreach ($meta_values as $key => $value) {
if ( substr($key, 0, 6) == "field_" ) {
$field_params = maybe_unserialize( $value[0] );
if( isset($field_params['name']) && $field_params['name'] == $acf_field_title )
$acf_field_key = $field_params['key'];
}
}
}
if( $acf_field_key != '' ) { // key found, can insert info
error_log('acf_field_key found: ' . $acf_field_key);
update_field( $acf_field_key, $data_to_insert, $event_id );
}
`
You can adapt it to get any field's key, not just repeaters.
Ideally there would be a function in the ACF's API to get the field key given the field name. Just saying! :)