Before running a command, I'm trying to check if a user already has a specific value (which is a Post ID) in a user meta key "saved_sessions". (This is a "favorites" type of system that assigns posts to a user, later to be returned for display of favorited sessions)

Note - this is NOT an array of ID's. Not sure why it was programmed that way, but it's the way it was.

The main function was coded by someone else and I'm looking to expand it's functionality, but my PHP is fairly greenish. The main function works, but it's adding another entry on each run so I'm adding an if statement to skip the adding a new entry if an existing matching entry already exists.

Thanks in advance.

    // Check if there are any registrations
    if ( $registrations ) {
        // Loop through each registration
        foreach ( $registrations as $registration ) {
            // Get the registered user
            $registered_user = $registration['registered_user'];
            // Get the user ID
            $user_id = $registered_user['ID'];
            // Check if Saved Session ID Already Exists for user
            if (?????) 
                // Add the post ID to the user meta if one does not exist
                add_user_meta($user_id, 'saved_session', $post_id);


1 Answer 1


If I understand correctly, you are wanting to prevent duplicate IDs in the meta data: use the get_user_meta() function to retrieve the meta value and check it for the ID (untested):

$meta = get_user_meta( $user_id, 'saved_session' );

if ( ! in_array( $post_id, $meta ) ) {
    add_user_meta( $user_id, 'saved_session', $post_id );

For others that may arrive here:

If the intent is to have only one value in saved_session, then the add_user_meta() function has a fourth parameter $unique that if set to true will prevent meta with an existing key from being updated or added to.

$unique bool Optional Whether the same key should not be added. Default: false

add_user_meta( $user_id, 'saved_session', $post_id, true );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.