英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论