2012-12-26 41 views
0

我試圖讓下面的代碼工作:WordPress的 - 爲什麼我不能在插件內使用條件標籤?

if(is_home()): 
    echo 'User is on the homepage.'; 
else: 
    echo 'User is not on the homepage'; 
endif; 

如果我把它放在主題頁眉或頁腳,然後它工作,但如果我把它放在我的插件,這是行不通的。我也嘗試過is_single()is_page(),並且它們在插件內部不起作用。任何想法是什麼問題?

回答

2

is_home()和幾個其他WP功能並不總是定義,請嘗試使用合適的hook來包含您的代碼。例如:

add_action('wp', 'check_home'); 
// or add_action('init', 'check_home'); 

function check_home($param) 
{ 
    if (is_home()): 
     echo 'User is on the homepage.'; 
    else: 
     echo 'User is not on the homepage'; 
    endif; 
} 

編輯:

在任何情況下,如果要回顯數據使用body標籤內的鉤。使用the_content鉤子的示例:

add_filter('the_content', 'check_home'); 

function check_home($content) 
{ 
    if (is_home()) 
     $echo = 'User is on the homepage.'; 
    else 
     $echo = 'User is not on the homepage'; 

    return $echo . '<hr />' . $content; 
} 
相關問題