The current result is “PHP Fatal error: Call to undefined function wp_get_current_user()” which makes sense, but doesn’t help.
I need to use $current_user.
Here is the code I’m currently using:
$wp->init();
do_action( 'init' ); // Check site status
$file='http://xxxxxxxx.com/wp-admin/wp_includes/pluggable.php';
if ( is_multisite() ) {
if ( true !== ( $file = ms_site_check() ) ) {
require( $file );
die();
}
unset($file);
}
// Get the current user's info
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
echo $current_user->user_login;
function paf_uname(){
return $current_user->user_login;
}
To add to @EAMann’s answer, you need to wrap your
wp_get_current_user()
call (or any call that tries to access a function defined withinpluggable.php
) within the'plugins_loaded'
action.So, if you’re putting this inside your
functions.php
file, do it like this:Do note that we’re not interested in what this function returns. We’re interested in when this function executes, namely, after the
pluggable.php
file has loaded and defined yourwp_get_current_user()
function.So, don’t expect to do anything with the return value for this function. Instead, consider this function as the starting point for everything that you want to do once you’ve got the current user’s info.
Doing it in a plugin
For the sake of completeness, here’s how you would access a similar pluggable function from within the context of your own plugin:
(put this inside a .php file inside your
plugins
folder)I’ve used this technique successfully for a very simple “Coming Soon” type of plugin that redirects the user to a specific page if they’re not logged in using
wp_safe_redirect()
.The problem is that you’re trying to load the code directly rather than with a WordPress hook. WordPress loads a bunch of code in a specific order (you can see the list of actions fired in a typical request in the Codex).
By trying to fire your code directly, you’re executing just before
pluggable.php
is loaded. And you should not try toinclude()
this file directly. Let WordPress do that for you.Instead, define a function that gets the user information:
You can then use this function anywhere in your theme without issue. For example:
If you need to use
$current_user
in other code, make sure you fire that code with a WordPress action … don’t call it directly or it will be executed before the function is available.It looks like you’re loading your code before certain functions are available. Have you tried:
Simply add this function to your plugin .php file
Then call it anywhere you want to get user login status. For example: