2012-12-26 100 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; 
} 
相关问题