WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] update_user_meta failure conditions (3 posts)

  1. robwil0
    Member
    Posted 1 year ago #

    I am coding a plugin that saves some metadata to the currently logged in user. I am using the function update_user_meta. I have noticed the following behavior:

    update_user_meta($uid, "mykey", "myvalue") => returns True for success

    followed by

    update_user_meta($uid, "mykey", "myvalue") => returns False for failure

    In other words, storing the same value as already exists leads to a return value that indicates failure. I assume this means that the underlying code is checking the MySQL affected rows, and 0 affected rows is being reported as a failure.

    Is there any way to get around this, so that storing the same value (successfully) again is reported as a success? I'm thinking that perhaps the optional $prev_value parameter of the update_user_meta function may be helpful here, but the documentation of its use is not clear to me.

    Any help would be appreciated. Thank you,

    robwil

  2. Björn Nordqvist
    Member
    Posted 1 year ago #

    I have never actually used this function but i would probably solve this by a conditional statement to define whether the value is already defined or successfully set.

    If ( get_user_meta($uid, "mykey", true) == "myvalue" ) {
       $status = true;
    } else {
       $status = update_user_meta($uid, "mykey", "myvalue");
    }
    
    if ( $status == true ) {
       // Function called on sucess
    }
  3. robwil0
    Member
    Posted 1 year ago #

    Simple but effective solution. I had to throw in a stripslashes() when testing equality due to my particular scenario, but otherwise worked perfectly. Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic