The determine_current_user WordPress PHP filter allows you to modify or determine the current user based on the request’s cookies.
Usage
add_filter('determine_current_user', 'your_custom_function', 10, 1);
function your_custom_function($user_id) {
// your custom code here
return $user_id;
}
Parameters
$user_id(int|false): User ID if one has been determined, false otherwise.
More information
See WordPress Developer Resources: determine_current_user
Examples
Modify user ID based on a custom condition
In this example, we’ll set the user ID to 42 if a custom condition is met.
add_filter('determine_current_user', 'change_user_id_based_on_condition', 10, 1);
function change_user_id_based_on_condition($user_id) {
if (your_custom_condition()) {
$user_id = 42;
}
return $user_id;
}
Prevent user login based on IP address
In this example, we’ll prevent users from logging in if their IP address is in a list of blocked IPs.
add_filter('determine_current_user', 'block_users_from_ip', 10, 1);
function block_users_from_ip($user_id) {
$blocked_ips = array('192.168.0.1', '192.168.0.2');
if (in_array($_SERVER['REMOTE_ADDR'], $blocked_ips)) {
return false;
}
return $user_id;
}
Set current user based on a custom authentication system
In this example, we’ll use a custom authentication system to set the current user.
add_filter('determine_current_user', 'set_user_based_on_custom_auth', 10, 1);
function set_user_based_on_custom_auth($user_id) {
$user_id_from_custom_auth = get_user_id_from_custom_auth();
if ($user_id_from_custom_auth) {
return $user_id_from_custom_auth;
}
return $user_id;
}
Allow guest users to be treated as a specific user
In this example, we’ll set a specific user ID for guests visiting the site.
add_filter('determine_current_user', 'set_guest_user_id', 10, 1);
function set_guest_user_id($user_id) {
if (!$user_id) {
return 42; // Set user ID to 42 for guest users
}
return $user_id;
}
Override user ID based on query parameter
In this example, we’ll override the user ID based on a query parameter in the URL.
add_filter('determine_current_user', 'override_user_id_with_query_parameter', 10, 1);
function override_user_id_with_query_parameter($user_id) {
if (isset($_GET['override_user_id']) && is_numeric($_GET['override_user_id'])) {
return (int)$_GET['override_user_id'];
}
return $user_id;
}