問題描述
當你在插件中使用與當前用戶相關(guān)的函數(shù)/判斷條件,諸如:
is_user_logged_in()
wp_get_current_user()
之類的時候,你會發(fā)現(xiàn)類似以下錯誤:
Fatal error: Call to undefined function is_user_logged_in()
或者:
Fatal error:Call to undefined function wp_get_current_user() ……
初步的想,你會覺得:is_user_logged_in() 和 wp_get_current_user()出錯的根本原因應(yīng)該是一致的,的確是這樣,那我們就拿前者說事兒,自覺忽略后者。
原因
為什么會這樣呢?在Wordpress.org官方的is_user_logged_in()函數(shù)的說明頁面,沒有說明這個判斷函數(shù)不能在插件中使用,但的確是不能使用的。只有一句描述:
This Conditional Tag checks if the current visitor is logged in. This is a boolean function, meaning it returns either TRUE or FALSE.
沒有任何notice 啊、tip啊之類的。只是在該頁面(http://codex.wordpress.org/Function_Reference/is_user_logged_in)的最后的related中,有一個:
Article: Introduction to WordPress conditional functions (這是個鏈接)
點擊那個鏈接進去,是Wordpress的條件標簽(Conditional Tags)綜合說明頁面,在這個頁面上,有這么一句話:
The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches.
可用于你的模板文件以怎么著,沒說插件的事兒。這是原因嗎,不是根本原因!不是的,根本原因是判斷用戶是在init這個action之后,而如果你的插件用的是plugins_loaded這個action,那么,它至少會比init早三個action載入,所以,在掛在這個Hook上的函數(shù)中就無法判斷/獲取當前用戶信息了,這應(yīng)該是根本原因了,解決這個問題的最簡單的方法其實很簡單的,如下。
解決
//如果不存在這個 is_user_logged_in 函數(shù),就引入pluggable.php文件
if(!function_exists('is_user_logged_in'))
require (ABSPATH . WPINC . '/pluggable.php');
//下面你就可以正常使用 is_user_logged_in() 函數(shù)啦
if(is_user_logged_in()) {
}
參考上面的樣例,修改你的插件代碼即可。
原創(chuàng)文章,僅發(fā)布在索凌網(wǎng)絡(luò)和WP大學(xué),謝絕轉(zhuǎn)載,如果真憋不住想轉(zhuǎn)載,請保留這段話和本文鏈接,否則,嘿嘿,你知道的!






WordPress中有很多地方都跟這里的現(xiàn)象很像,即一個執(zhí)行順序問題,我們一般采用掛載不同的action hook來實現(xiàn)。比如你說的這個問題,我們可以把插件中的動作放到init后面執(zhí)行,即function里面套function,避免由于部分內(nèi)核沒有加載。