I’ve been asked to add a sort of safety mechanism to a site where a user can only access their profile if they have a cookie set after logging in, and they can only have a maximum of 3 cookies. I’ve made a table in the database to store the cookies, so I can keep count of them.
I don’t really know how WordPress works, but I’ve been able to find out that I need to edit the theme’s functions.php
file and add an action using wp_login
. I’ve edited the functions.php
file, added the action, request the user ID, and it returns 0
. I know that this is how wp_get_current_user
is supposed to work, it returns 0
if there’s no one logged in; however the user IS logged in, but it still won’t return the ID. Here’s the code:
add_action( 'wp_login', 'login_cookie' );
function login_cookie() {
global $wpdb;
$user = wp_get_current_user();
//Get current user
$id = $user->ID;
if(!isset($_COOKIE['userCookie'])) {
// Query the database to see how many cookies they have used
$cookie_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_cookies WHERE user_id=".$id."");
// If the returned value is bigger or equal to 3 than the user cannot login
// they will be logged out, and redirected
if($cookie_count >= 3) {
wp_logout();
wp_redirect("");
}
//Else they can login and they recieve a new cookie, which will get inserted into the database
else {
$value = password_hash($id,PASSWORD_DEFAULT);
setcookie('userCookie', $value, time()+360000*24*100, "", "",false);
$wpdb->insert(
"wp_cookies",
[ 'user_id'=>$id, 'cookie_value'=>$value ],
[ '%d', '%s' ]
);
}
}
}
Also this should only affect normal users, not admins. Any ideas for that?
2 Answers
wp_login
hook provides access to two parameters: $user->user_login
(string) and $user
( WP_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add_action() call:
function login_cookie($user_login, $user) {
global $wpdb;
var_dump($user); // get WP_User object
//Get current user ID
$id = $user->ID;
.....
}
add_action( 'wp_login', 'login_cookie', 10, 2 );