How to determine if an admin is logged in outside the loop

I need to be able to tell if an admin is logged in ouside of the loop.

This is needed for some php files that are part of a WP site but do not use require( '../wp-load.php );

What I need to do is keep the Google Analytics tracker JS from firing for logged in admins, but track everyone else.

How do I find out if an admin is logged in outside of the loop? Checking the WP logged in cookie? Or must I use wp-load.php?

Topic outside-wordpress loop admin login Wordpress

Category Web


You can use current_user_can() to determine if an admin user is logged and load your Google tracking code using wp_enqueue_script with an if statement in functions.php

if ( ! current_user_can( 'edit_posts' ) ) {
        wp_enqueue_script( 'google-tracking');
    } 

Either use wp-load.php (performance taxing) or do the following:

// Capture 'init' event in a plugin placed in /wp-content/mu-plugins/
// This will keep the shared cookie fresh for each load.
add_action('init', function(){
    $cookie_server = $_SERVER['SERVER_NAME'];
    // To work an all subdomains uncomment:
    // $cookie_server = strchr($_SERVER['SERVER_NAME'], '.');
    // Now check if current user is an Admin and do this: Signal Admin presence by
    // setting up a special value cookie that you can detect in your other script.
    // Prepare a salt and a hash here caculated from $salt, User-Agent and Remote IP
    $special_salt = 'setup a string here others will not know';
    $special_hash = md5($_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$special_salt);
    if(!current_user_can('activate_plugins')){
        // If the user is not an admin remove the special cookie (if exists)
        setcookie('crosscript_auth', null, time() - 24 * 3600, '/', $cookie_server, is_ssl(), true);
    }else{
        // If the user is an admin add the special cookie with the $special_hash value
        setcookie('crosscript_auth', $special_hash, strtotime('+1 week'), '/', $cookie_server, is_ssl(), true);
    }
    // Now, in your other script, use the $special_salt and $special_hash from here
    // to compare to the $_COOKIE['crosscript_auth'], if available.
    // That will tell you if an Admin is logged in
}); // PHP 5.3 Closure, just change to named function for 5.2

Just read the comments in the code. I tried to describe the entire logic behind it there. It's pretty safe and the special Cookie is bound to the IP/User-Agent. With a proper salt you should not have problems unless a very 1337 hacker targets you :) Also it's a start for you to tweak on.

Regards.

PS: For any other clarifications, don't hesitate to ask.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.