I’m trying to display something to my wordpress site users depending on the number of times they have logged in. I’ve tried to accomplish this using user_meta and the wp_login hook.
add_action( 'wp_login', 'survey_login' );
function survey_login() {
global $current_user;
get_currentuserinfo();
$login_count = get_user_meta($current_user->ID, 'login_count', true);
if($login_count == "") { $login_count = 0; }
update_user_meta($current_user->ID, "login_count", $login_count++ );
if($login_count >= 5) {
$_SESSION['csm_survey_login'] = true;
}
}
This seems like it should work, but for some reason the user_meta key only gets added/updated about 1/20th of the time. I’ve been able to find no pattern to how or why.
I’ve tried simplifying the function to simply
add_user_meta($current_user->ID, 'login_count', 1);
Or
update_user_meta($current_user->ID, 'login_count', 1);
Both are giving me the same trouble.
Anyone know why update_user_meta or wp_login may only work a fraction of the time?
The first time this is loaded the meta key won’t exist, if a meta key can’t be found the function with return
false
not an empty string, and you can’t incrementfalse
. Don’t useempty()
as this will return true for0
, but to test for false instead of an empty string use:The problem is with your incrementing.
$login_count++
returns the current value of$login_count
and then increments. You want++$login_count
which returns the incremented value.Cheers.