Wordpress使用functions.php仅在特定页面模板上运行功能

Ila*_*sda 0 wordpress wordpress-theming

我有一个以下代码来检查当前使用的文件是否是tmp_home_page.php,但是当我这样做echo $template_file;时显示functions.php

    add_action('template_redirect', 'are_we_home_yet', 10);
    function are_we_home_yet(){
            global $template;
            $template_file = basename((__FILE__).$template);
            if ( is_home() && $template_file == 'tmp_home_page.php' ) {

            // do stuff

            }
     }
Run Code Online (Sandbox Code Playgroud)

知道如何确保我do stuff只在主页上运行,并且当使用给定的模板时?

Xhy*_*ynk 6

你看起来太难了,有一个wordpress功能. is_page_template()

if( is_page_template( 'tmp_home_page.php' ) && is_home() ){
    // Do Stuff
}
Run Code Online (Sandbox Code Playgroud)

此外,is_front_page()通常是is_home()在尝试确定用户是否正在查看WordPress站点的Front/First Page时更好的替代方法.你可以看到更多的关于这个问题在这里.