Basicly i want to check if a row exist in the metadata in wordpress. If the metakey table for that user does not exist it should make one. This code i am using right now and it works but it seems buggy. I have recently notice that some users have two to five meta_key called credits now with value 0. Is there a better way to check if a meta_key already exist for the user or not?
<?php
global $current_user;
global $wpdb;
$useridvip=$current_user->ID;
$credits=$current_user->credits;
if (empty($credits)) {
$wpdb->insert( "wp_usermeta", array( 'umeta_id' => null, 'user_id' => $useridvip, 'meta_key' => credits, 'meta_value' => 0 ) );
$credits="0";
}
else { echo "all good"; }
Have not tested this but the first thing I'd do just for good measure is make sure this is wrapped in is_user_logged_in()
if(is_user_logged_in()) {
//then put your check/update code here
}
Inside of that, you could try...
global $current_user;
$useridvip=$current_user->ID;
$credits = get_user_meta($useridvip, 'credits', true);
if($credits == '') {
add_user_meta( $useridvip, 'credits', 0, true );
}
Generally speaking, you should try to rely upon get_user_meta and add_user_meta when possible.
I think this will still create multiple meta_key entries if the current user_meta credits
is storing ''. Instead what you could do is try
update_user_meta( $useridvip, 'credits', 0 );
which Returns (int/boolean). Meta ID if the key didn't exist, true on successful update, false on failure.
So if you receive the meta ID back you would do
add_user_meta( $useridvip, 'credits', 0, true );