I have a script outside wordpress directory where I need to check if the user is currently logged in as admin.
Website structure is:
/home/myscript.php
/home/wordpress/check_if_admin.php
check_if_admin.php
content is:
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID;
//usually admin user id is 1 if its not working check admin user id from wp_users table
if($user_id == 1) {
$admin = "1";
}
$is_admin = current_user_can( 'manage_options' );
if ( current_user_can( 'administrator' ) ) {
$admin = "1";
}
if (!empty($_GET['debug'])) {
echo "UID $user_id / ADM $admin";
}
If I run the script from /home/wordpress/check_if_admin.php
it works.
But if I try to include check_if_admin.php
inside myscript.php
, it doesn’t work and the $user_id / $admin
is always zero.
How can I check the admin status in myscript.php
?
Try adding with absolute path.
If your script is outside the wordpress directory, you need to add the following lines to your wp-config.php before
require_once(ABSPATH . 'wp-settings.php');
This is because by default, your login cookie is only accessible to your wordpress directory.