Reputation: 461
My goal is to create a plugin for counting the number of times a user logs in. But for now, it seems the update_user_meta() is not working or I'm not using it properly. I'm just trying to update a custom variable with the user_id value, so that I can know that I am storing a value in the user_meta.
<?php
function user_login_count2($redirect_to, $request, $user) {
global $user;
global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID;
if (isset($user_id)) {
if ( get_user_meta($user_id, 'login_count2', true) ){
//$login_count2 = get_user_meta($user_id, 'login_count2', true);
//$login_count2++;
//update_user_meta($user_id, 'login_count2', $login_count2);
$user_id_test = get_user_meta($user_id, 'user_id_test', true);
update_user_meta($user_id, 'user_id_test', $user_id);
}else{
add_user_meta($user_id, 'login_count2', '1');
}
}else{
return $redirect_to;
}
}
add_filter('login_redirect', 'user_login_count2', 10, 3);
function show_login_counts() {
global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID;
$user_id_test = get_user_meta($user_id, 'user_id_test', true);
if(isset($_GET['ict']) && $_GET['ict'] == 1){
echo $user_id;
echo $user_id_test;
}
}
add_action('wp_footer', 'show_login_counts');
?>
Upvotes: 0
Views: 3525
Reputation: 6275
It's a little hard to follow your code with all the commented out code, and I'm not sure what the purpose of the calls to the various user functions are variables are.
Here's how I would do it:
add_action('wp_login', 'record_user_login', 10, 2);
function record_user_login($user_login, $user){
// Get current user ID from the user object
$user_id = $user->ID;
// Get previous login count
$login_count = get_user_meta($user_id, 'login_count', true);
// Increment login count if it exists, or set it to 1
if (int_var($login_count)){
$new_count = $login_count++;
}
else {
$new_count = 1;
}
// Update login count in user meta
update_user_meta($user_id, 'login_count', $new_count);
}
Upvotes: 1