Get current username in a blank php page (wordpress)

I searched the Stack Overflow website to get a proper answer (that works) but unfortunately nothing worked…

It’s a simple question, I just need to output the current users username!

Read More

I found a code on stackoverflow which is the following:

<?php
$user_id = get_current_user_id();
echo "ID User : ".$user_id ;
if ($user_id == 0) {
    echo 'You are currently not logged in.';
} else {
    echo 'You are logged in as user '.$user_id;
}
?> 

^^found it on this site

When I do this I get an error:

Fatal error: Call to undefined function get_current_user_id() in
/home/heal/public_html/mysite.com/index.php on line 14

I’m using wordpress version 3.3.1

Related posts

Leave a Reply

2 comments

  1. I think you need to access global variables and for that you need to load wordpress in your new page.

    if ( !defined('__DIR__') ) define('__DIR__', dirname(__FILE__)); //getting current directory using magic constants __DIR__ is deprecated in php 5.3.+
    $path = explode('wp-content',__DIR__); //getting main web root path for including further files.
    include_once($path[0].'wp-load.php'); //for getting global variables like wpdb 
        global $current_user;
    
        echo $current_user->user_login;
    

    After adding above you can now access global variables. user_login will print username. I hope that helps you. Also i agree with @j3frea. Here i have shown you the hint in which i was trying to implement plugin,so i exploded it using ‘wp-content’.

  2. At http://codex.wordpress.org/Function_Reference/get_currentuserinfo

    It suggests that you’re looking for $current_user->user_login

    Their default example is:

    <?php global $current_user;
      get_currentuserinfo();
    
      echo 'Username: ' . $current_user->user_login . "n";
      echo 'User email: ' . $current_user->user_email . "n";
      echo 'User first name: ' . $current_user->user_firstname . "n";
      echo 'User last name: ' . $current_user->user_lastname . "n";
      echo 'User display name: ' . $current_user->display_name . "n";
      echo 'User ID: ' . $current_user->ID . "n";
    ?>
    

    I must admit though, if you’re getting Call to undefined function get_current_user_id() then it’s more likely that wordpress is not correctly installed or something of that nature.

    I wonder why you are editing index.php -> wordpress does the frontend stuff for you, perhaps you should be looking at theming.