Support

Account

Home Forums ACF PRO update_field and User Field Type

Solved

update_field and User Field Type

  • Hi

    I’ve been with ACF for a few years now and it is a part of every project I build.

    I have a website that a user can click “Follow” on author page and I would like to save that info in User Field Type called “user_followed_users”.

    All works good so far, however in database the info is saved as serialized object of that user. Moreover if I select multiple users, it is saved as an array of user objects.

    How can easily add/remove users from the list and update is through update_field?

    Currently I have a solution but it takes 50 lines of code just to create new array of IDs. Is there a better way.

  • Here is my optimized code if needed.

    if ( (is_user_logged_in()) && ($_GET['action'] == 'follow') ) {
    	$user_followed_users = get_field('user_followed_users', 'user_'.$current_user->ID);
    	$user_followed_users_temp = array();
    	if (is_array($user_followed_users)) {
    		foreach($user_followed_users as $user) {
    			$user_followed_users_temp[] = $user['ID'];
    		}
    		if (!in_array($curauth->ID, $user_followed_users_temp)) {
    			$user_followed_users_temp[] = $curauth->ID;
    		} else {
    			// Clicking twice will remove the user form user followed list
    			if(($key = array_search($curauth->ID, $user_followed_users_temp)) !== false) {
    				unset($user_followed_users_temp[$key]);
    			}
    		}
    	} else {
    		$user_followed_users_temp = array($curauth->ID);
    	}
    	update_field('user_followed_users', $user_followed_users_temp, 'user_'.$current_user->ID);
    }
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.