Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress ACF: How to add rows to a repeater field attached to a user via custom code (PHP)

I have been through the ACF and ACF Repeater Field documentation but it has left me a little bit confused.

I have a bunch of users and I have (through ACF) attached a repeater field to each of them (called Events), the repeater field has a sub-field called Event ID (event_id).

Now the dilemma I have is that I want to be able to add and remove rows of event_id from the user depending on which events they have tried to add and remove.

I know of the update_field($field_key, $value, $post_id) function but I'm not too sure how to utilise it to add rows into sub-fields of a repeater field attached to a user. I also need some direction as to how to remove items.

Any help is appreciated!

like image 760
PavKR Avatar asked Jul 22 '14 05:07

PavKR


1 Answers

To add rows into sub-fields of a repeater field, you can do:

$field_key = "repeater_field";
$user_id = "user_123"; // save to user (user id = 123)

$value = get_field($field_key, $user_id);
$value[] = array("event_id " => 25);
$value[] = array("event_id " => 30);
update_field( $field_key, $value, $user_id );

To remove items, I'd use a PHP function such as the one in the accepted answer at Delete element from multidimensional-array based on value:

$value = removeElementWithValue($value, "event_id", 25);
update_field( $field_key, $value, $user_id );

As to where to add these codes (ie. the action hook) depends on when you'd like to add/remove the items.

like image 158
Angelie Macalansag Avatar answered Nov 19 '22 05:11

Angelie Macalansag