WordPress ACF update_field with a user field

Using Advanced Custom Fields for a wordpress site I create a custom field for Users and its type is “User”, it is also set to support multiple selection. The idea is to link users to each other as friends.

Edit_Field_Group_‹_Zoomup_—_WordPress

Edit_User_‹_Zoomup_—_WordPress_et_Zoomup_2016-04-15_02-00-03_et_Organizer

To update the field I used update_field() but it me took time to figure out how to make it work.

At first I tried to push the new user id to the field :

<?php

// ADDING friend
$user_id = 'user_1';   // user id = 1
$new_friend_id = 2;

// retrieve current friends
$friends = get_field('friends', $user_id);
$friends[] = $new_friend_id;

// update field
update_field('friends', $friends, $user_id);

?>

But unfortunately this doesn’t work, for more than one user you should expect the wrong user to be added, the same for removing friend :

<?php

// REMOVING friend
$user_id = 'user_1';   // user id = 1
$friend_id_to_remove = 2;

// remove friend
foreach ($friends as $key => $friend) {
if($friend['ID'] != $friend_id_to_remove) {
unset($friends[$key]);
// or array_splice($friends, $key, 1);
break;
}
}

// update field
update_field('friends', $friends, $user_id);

?>

To make it work you have to create a new array and populate it with same type of datas :

<?php

// ADDING friend
$user_id = 'user_1';   // user id = 1
$new_friend_id = 2;
$newfriends = array();

// retrieve current friends
$friends = get_field('friends', $user_id);

foreach ($friends as $key => $friend) {
array_push($newfriends, $friend['ID']);
}

// add new user
array_push($newfriends, $new_friend_id);

// update field
update_field('friends', $newfriends, $user_id);

?>

And the same to remove a friend :

<?php

// REMOVING friend
$user_id = 'user_1';   // user id = 1
$friend_id_to_remove = 2;
$newfriends = array();

// retrieve current friends
$friends = get_field('friends', $user_id);

foreach ($friends as $key => $friend) {
if($friend['ID'] != $friend_id_to_remove) {
array_push($newfriends, $friend['ID']);
}
}

// update field
update_field('friends', $newfriends, $user_id);

?>

You can notice that the value of the custom field is an array of object and the one we create is only an array of ids.

Leave a Reply

Your email address will not be published. Required fields are marked *