Hi Elliott,
sorry for the delay in getting back to you – I’ve been working on other projects.
It turns out my code was nearly correct. What I needed to do when no value exist was have an array of arrays.
So, I have just added one line to my code, and it seems to be working now
function acf_add_repeater_row($field_name, $post_id, $values, $field_key = '') {
$field_obj = get_field_object($field_name, $post_id );
if( $field_key == ''){
$field_key = $field_obj['key'];
}
// check whether the meta fields exist in the DB
if( $field_obj['value'] ) {
// they do, let's add a row
array_push( $field_obj['value'], $values );
update_field( $field_key, $field_obj['value'], $post_id );
}
else if ($field_key) {
// they don't, let's create them
$values = array( $values );
update_field( $field_key, $values, $post_id );
}
}
The only thing that is left is finding the field key programmatically, rather than having to hard code it
Adam
Hi @elliot – thanks very much for your response.
I have altered the function so that I can pass it the field key – is there really know way to find this?
I have one final problem, if you don’t mind? My code is below, it is not correctly inserting the data when no rows exist already (the second update_field call).
Thanks,
Adam
function acf_add_repeater_row($field_name, $post_id, $values, $field_key = '') {
$field_obj = get_field_object($field_name, $post_id );
// var_dump($field_obj['value']);
if( $field_key == ''){
$field_key = $field_obj['key'];
}
// check whether the meta fields exist in the DB
if( $field_obj['value'] ) {
// they do, let's add a row
array_push( $field_obj['value'], $values );
update_field( $field_key, $field_obj['value'], $post_id );
}
else if ($field_key) {
// they don't, let's create them
update_field( $field_key, $values, $post_id );
}
}