Get current user data from external PHP page

I have a PHP page at the same level as the template/theme on WordPress.
I need to be able to get the current logged in user details from this page.

I have tried this:

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

global $current_user;
$current_user = wp_get_current_user();
var_dump( $current_user );

But it’s returning nothing. 0 as user_id and nothing on the other fields. Am I missing something?

UPDATE:

This is the result of the var_dump:

object Object]1object(WP_User)#79 (10) {
      ["data"]       => NULL
      ["ID"]         => int(0)
      ["id"]         => int(0)
      ["caps"]       => array(0) {}
      ["cap_key"]    => NULL
      ["roles"]      => array(0) {}
      ["allcaps"]    => array(0) {}
      ["first_name"] => string(0) ""
      ["last_name"]  => string(0) ""
      ["filter"]     => NULL
    }

3 Answers
3

You can…

Load the file into the file where you want to display the ‘hey username’ message:

<?php include(TEMPLATEPATH .'/check-user-hello.php'); ?>

.
Then in that file “check-user-hello.php”
You need to put this code

<?php
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
echo 'Hey ' . $current_user->display_name;
} else {
echo '<a href="'. get_bloginfo('url') .'/wp-admin" class="loginlinktop">Login</a>';
}
?>

.
Hope This Helps 🙂

TO learn more about this subject:

  • get_currentuserinfo();

  • Is User Logged In

.
FIX 3

To the best of my knowledge you need to grab wp-blog-header.php in order to run WordPress functions outside of the loop.. so.. try this.

<?php

require('../../../wp-blog-header.php');

if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
echo 'Hey ' . $current_user->display_name;
} else {
echo '<a href="'. get_bloginfo('url') .'/wp-admin" class="loginlinktop">Login</a>';
}
?>

.
Please NOTE:
THE “wp header blog” PATH i have created in this code is assuming your file is in your template directory.. if its not you should change the path of require so it would load the file correctly.

Leave a Comment