如何在包含Ajax功能之前检查页面模板?

huangapple go评论75阅读模式
英文:

How to check for a pagetemplate before include Ajax functionality?

问题

这是我正在尝试做的事情:

在我的functions.php中,我有一个加载实现AJAX功能的类的函数。

$ajaxClass = '\\Theme\\Ajax\\' . $name;
new $ajaxClass;

这就是我遇到困难的地方。我现在尝试使用get_page_template()来验证模板名称,但那不起作用。通过挂钩加载整个内容也不起作用。要么关联的JS没有加载,要么在执行AJAX调用时我收到"Bad Request"。

如果没有模板名称的检查,一切都正常工作。

有人可以给我一些建议吗?

英文:

Here's what I'm trying to do:

i have a function in my functions.php which loads a class that implements AJAX functionality.

            $ajaxClass = '\\Theme\\Ajax\\' . $name;
            new $ajaxClass;

And this is where I get stuck. I try to verify the template name with get_page_template() now, but that doesn't work. Loading the whole thing via a hook didn't work either. Either the associated JS is not loaded or I get a "Bad Request" back when executing the AJAX call.

Without the check on the template name everything works fine.

Can someone please give me a tip?

答案1

得分: 0

我建议用于确定页面模板的最早挂钩是template_redirect。从这个挂钩中,您可以使用条件函数来确定请求是什么,并且是否要加载您的AJAX类(未经测试):

add_action( 'template_redirect', static function () {

    // Conditionally initialize the AJAX class.
    if ( 'uses-ajax.php' !== get_page_template() ) {
        return;
    }

    $name = ''; // define

    $ajaxClass = '\\Theme\\Ajax\\' . $name;
    new $ajaxClass;
} );
英文:

The earliest hook I'd recommend for determining the page template is template_redirect. From this hook, you can use conditional functions to determine what the request is for, and whether to load your AJAX class (untested):

add_action( 'template_redirect', static function () {

    // Conditionally initialize the AJAX class.
    if ( 'uses-ajax.php' !== get_page_template() ) {
        return;
    }

    $name = ''; // define

    $ajaxClass = '\\Theme\\Ajax\\' . $name;
    new $ajaxClass;
} );

</details>



huangapple
  • 本文由 发表于 2023年6月8日 23:44:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定