2016-03-20 245 views
1

get_current_user_id()對於以下代碼返回0。我嘗試了一些可用的堆棧溢出解決方案,但不知何故不適合我。我期待解釋爲什麼它返回零和如何解決?get_current_user_id()返回0 0

P.S:我從外部php頁面調用了get_current_user_id(),其中包括'../wp-blog-header.php'

代碼:

<?php 
require('../wp-blog-header.php'); 
get_header(); 

$user_ID = get_current_user_id(); 
echo $user_ID; 

?> 

回答

2

你必須調用用戶認證的wordpress進程。嘗試get_current_user_id();前加入以下代碼,如果它不解決您的問題,它至少會點你朝着正確的方向:

$user_id = apply_filters('determine_current_user', false); 
wp_set_current_user($user_id); 

希望它能幫助!

+0

太棒了,它幫助了我。 –

1

這可能是在外部文件中直接包含wp-blog-header.php的結果。來自the Codex on get_current_user_id()

用戶的ID,如果有當前用戶;否則爲0

我不知道你想做什麼,但正確的方法是這樣的邏輯下的正確action hook,或writing a custom plugin添加到的functions.php。通過執行這兩項操作之一,您將可以訪問經過身份驗證的用戶。