Skip to content

Instantly share code, notes, and snippets.

@thelovekesh
Created March 20, 2022 08:58
Show Gist options
  • Select an option

  • Save thelovekesh/8473a2813c703b4313a15afc8cf67993 to your computer and use it in GitHub Desktop.

Select an option

Save thelovekesh/8473a2813c703b4313a15afc8cf67993 to your computer and use it in GitHub Desktop.
Find whether a user is logged in or not from the user ID in WordPress
<?php
/**
* Plugin Name: Find Logged-in User by ID
* Author: thelovekesh
* Description: This plugin will find the logged-in user by ID.
* Text Domain: thelovekesh
*
* @package thelovekesh
*/
add_action(
'wp_footer',
function() {
echo '<button id="get-user">Get Logged In User</button>';
?>
<script>
const getUsersBtn = document.getElementById('get-user');
const ajaxUrl = '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>';
const nonce = '<?php echo esc_html( wp_create_nonce( 'get-users' ) ); ?>';
const userId = 1;
getUsersBtn.addEventListener('click', function() {
fetch(ajaxUrl, {
method: 'POST',
body: `action=get_users&user_id=${userId}&nonce=${nonce}`,
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}),
credentials: 'same-origin',
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
});
</script>
<?php
}
);
/**
* Find logged in user by ID
*
* @return void
*/
function thelovekesh_find_logged_in_user() {
// verify nonce and use wp_unslash.
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'get-users' ) ) {
wp_send_json_error( __( 'Invalid nonce', 'thelovekesh' ) );
}
// get userId.
$user_id = isset( $_POST['user_id'] ) ? sanitize_text_field( wp_unslash( $_POST['user_id'] ) ) : '';
if ( ! $user_id ) {
wp_send_json_error( __( 'Invalid user id', 'thelovekesh' ) );
}
$all_logged_in_users = get_users(
array(
'meta_key' => 'session_tokens', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
'meta_compare' => 'EXISTS',
)
);
// match userId.
$all_logged_in_users = array_filter(
$all_logged_in_users,
function( $user ) use ( $user_id ) {
return $user->ID === $user_id;
}
);
if ( ! $all_logged_in_users ) {
wp_send_json_error( __( 'No logged in user found with given id', 'thelovekesh' ) );
}
wp_send_json_success( $all_logged_in_users );
exit;
}
add_action( 'wp_ajax_get_users', 'thelovekesh_find_logged_in_user' );
add_action( 'wp_ajax_nopriv_get_users', 'thelovekesh_find_logged_in_user' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment