Wordpress 使用functions.php 仅在特定页面模板上运行函数 [英] Wordpress use functions.php to run function only on specific page template

查看:32
本文介绍了Wordpress 使用functions.php 仅在特定页面模板上运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来检查当前使用的文件是否为 tmp_home_page.php,但是当我执行 echo $template_file; 时,它显示 functions.php

I have a following code to check if current used file is tmp_home_page.php, but when I do echo $template_file; it is showing 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

            }
     }

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

Any idea how to make sure that my do stuff is only run on home page and when given template is in use?

推荐答案

你对这个问题太认真了,有一个 wordpress 函数可以解决这个问题.is_page_template()

You're looking way too hard into this, there's a wordpress function for that. is_page_template()

if( is_page_template( 'tmp_home_page.php' ) && is_home() ){
    // Do Stuff
}

另外,is_front_page() 通常是尝试时 is_home() 的更好替代方案确定用户是否正在查看 WordPress 网站的首页/首页.您可以在此处查看有关该主题的更多信息.

Also, is_front_page() is usually a better alternative to is_home() when trying to determine if a user is viewing the Front/First Page of a WordPress site. You can see more on that subject here.

这篇关于Wordpress 使用functions.php 仅在特定页面模板上运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆