I’m new to wordpress and modifying the code that’s already working on a website. I want to get user’s ID but I haven’t figured out yet how. The following sample code works on my local environment but it only returs 0 for a user ID on the production site. Any idea would be appreciated.
<?php
$docroot = "/home/production-site/www";
require_once $docroot . '/wp-includes/pluggable.php';
testGetUserid();
function testGetUserid(){
echo 'Before wp_get_current_user <br />';
$user = wp_get_current_user();
echo 'After wp_get_current_user <br />';
echo 'ID= ' . $user->ID . '<br />';
}
?>
Btw, though I don’t know if this is relevant, to me it seems something strange might be occurring in wp-includes/pluggable.php
, so I uploaded the entire php file here to allow everyone to take a look at the file. And with this file, I had to require_once
following files on my local env.
require_once 'capabilities.php';
require_once 'functions.php';
require_once 'load.php';
require_once 'plugin.php';
require_once 'user.php';
Env production site: WordPress Ver 3.2.1, others unknown (using sakura.ne.jp hosting service)
Env local: Ubuntu 11.04, Apache/2.2.17, PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch (cli) (built: May 2 2011 23:00:17), WordPress Ver 3.2.1
Update June 10, 2012) In addition to everyone’s suggestions, @shabushabu (what a name 🙂 I’m Japanese) pointed out the last key factor – init
hook. Here’s what worked for me:
require( dirname(__FILE__) . '/../wp-load.php' ); // Path depends on your file structure, needless to say
:
do_action( 'login_init' );
: // Whatever you want to do
wp_get_current_user()
is actually just a wrapper for$current_user
andget_currentuserinfo()
, so you can use both. It’s important, though, to only call it on or after theinit
hook. Calling it before will only return 0, as you’ve experienced.Just use
$current_user
global, your function will be something like this:Use
global $current_user
, followed byget_currentuserinfo()
.$current_user
holds the information of the currently logged in user. You can also usecurrent_user_can()
to check the current user’s role.Remove all those includes, they aren’t required!