2012-01-04 194 views
2

我搜索了堆棧溢出網站以獲得正確的答案(的作品),但遺憾的是沒有什麼工作......獲取當前用戶名

這是一個簡單的問題,我只需要輸出當前用戶的用戶名!

我發現了一個計算器代碼如下:

<?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; 
} 
?> 

^^發現在這個網站上

當我這樣做,我得到一個錯誤:

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

我'm using wordpress version 3.3.1

+2

你試過這個之前加載了wordpress庫嗎?僅僅因爲安裝了wordpress並不意味着你可以在任何joe-random PHP腳本中開始調用WP函數。 – 2012-01-04 18:48:15

+0

你在代碼中的哪個位置嘗試添加這個snippit?有必要的wp庫在它之前被加載?嘗試提供整個腳本,這可以更容易地弄清楚。 – 2012-01-04 18:51:21

回答

2

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

這表明,你正在尋找$current_user->user_login

其默認的例子是:

<?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"; 
?> 

我必須承認,雖然,如果你得到Call to undefined function get_current_user_id()那麼它更有可能的是WordPress是安裝不正確或者這種性質的東西。

我想知道你爲什麼編輯index.php - > wordpress爲你做了前端的東西,也許你應該看看主題。

+0

我再次得到同樣的錯誤....他不認識那個功能! :( 致命錯誤:調用未定義的函數get_currentuserinfo()在/home/heal/public_html/mysite.com/index.php在第16行 – user1130577 2012-01-04 19:01:04

+0

好吧,你爲什麼要編輯index.php? - 看起來可能是某種東西做與主題... – jcuenod 2012-01-04 19:05:14

+0

我正在index2.php,我改變了你們的名字:p 不編輯index.php或我會毀了一切:p – user1130577 2012-01-04 19:10:15

5

我認爲你需要訪問全局變量,因此你需要在你的新頁面加載wordpress。

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; 

添加上面後,您現在可以訪問全局變量。 user_login將打印用戶名。我希望這可以幫助你。我同意@ j3frea。在這裏,我向你展示了我試圖實現插件的提示,所以我使用'wp-content'對其進行了分解。

+0

驚訝...... – Kamal 2012-01-05 06:03:05

+0

正是w我想要.... – user1589754 2014-04-27 16:34:37