Reputation: 1397
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?
Upvotes: 1
Views: 5205
Reputation: 27609
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 increment false
. Don't use empty()
as this will return true for 0
, but to test for false instead of an empty string use:
add_action( 'wp_login', 'survey_login' );
function survey_login() {
global $current_user;
get_currentuserinfo();
// Get meta key, returns false if it doesn't exist
$login_count = get_user_meta( $current_user->ID, 'login_count', true );
// Test for false and set to default
if ( false === $login_count ){
$login_count = 0;
}
// Increment and update
update_user_meta( $current_user->ID, "login_count", ++$login_count );
if( $login_count >= 5 ) {
$_SESSION['csm_survey_login'] = true;
}
}
Upvotes: 2
Reputation: 5249
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.
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;
}
}
Cheers.
Upvotes: 2