Skip to content

Instantly share code, notes, and snippets.

@alordiel
Created May 17, 2021 15:58
Show Gist options
  • Save alordiel/dd320e521120567868cda9ef62e0a1a8 to your computer and use it in GitHub Desktop.
Save alordiel/dd320e521120567868cda9ef62e0a1a8 to your computer and use it in GitHub Desktop.
WordPress: check if user is an adminstrator only by the wordpress_logged_in cookie (in case we need to do this check too early in the initialization of WP).
function is_user_administrator(): bool {
if ( function_exists( 'get_site_option' ) ) {
$siteurl = get_site_option( 'siteurl' );
if ( $siteurl ) {
global $wpdb;
$cookie_hash = 'wordpress_logged_in_' . md5( $siteurl );
if ( ! isset( $_COOKIE[ $cookie_hash ] ) ) {
return false;
}
$cookie = $_COOKIE[ $cookie_hash ];
$cookie_parts = explode( '|', $cookie ); // 0 => user_login, 1 => expiration, 2 => token, 3 => hmac
// check if the cookie has the correct number of parts
if ( count( $cookie_parts ) !== 4 ) {
return false;
}
$user_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_login = %s", $cookie_parts[0] ) );
if ( ! empty( $user_id ) ) {
$capabilities = $wpdb->prefix . 'capabilities';
$roles = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = '$capabilities'", $user_id ) );
if ( empty( $roles ) ) {
return false;
}
return strpos( $roles, 'administrator' ) !== false;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment