Search code examples
wordpressadvanced-custom-fieldsacfpro

ACF: Check Relationship and Add/Remove


I’m trying to create a “bookmark” button of sorts … where when the user bookmarks a post, I save it to a Relationship field. If the user then unbookmarks it, I check the relationship field and remove it from the collection of relationships.

Adding is easy. Removing is proving to be a pain in the butt and just destroys the entire array:

$current_bookmarks = get_field( 'webinar_bookmarks', 'user_' . get_current_user_id() );
    
    if ( in_array($webinar_post, $current_bookmarks) ) : // bookmarked, remove
    
        $key = array_search($webinar_post, $current_bookmarks);
        unset($current_bookmarks, $key);
    
    else : // not bookmarked, add

I'm assuming that because the array is serialized, the key is wrong? I can't be sure enough.

Is there a more official way of checking the current relationship array, and if it exists, removing it?

Thanks!


Solution

  • Here is the answer:

    unset($current_bookmarks[$key]);
        
    $updated_bookmarks = $current_bookmarks;