我目前正在通过ajax调用下一页的帖子。我使用jQuery发出请求,在php处理程序函数中构建一个自定义查询,遍历它,然后发送回HTML。这是我的循环:
$args = $_REQUEST[\'query\'];
$request_query = new WP_Query($args);
if ($request_query->have_posts()) {
while ($request_query->have_posts()) {
$request_query->the_post();
if ($post->post_type == \'foo\') {
get_template_part(\'/parts/thumbnail-templates/foo\');
} else if ($post->post_type == \'bar\') {
get_template_part(\'/parts/thumbnail-templates/bar\');
} else {
get_template_part(\'/parts/thumbnail-templates/generic\');
}
}
}
一切正常,循环按预期运行,除了我得到一个错误$post
没有定义,所以我的两个if
s失败,以及我的模板中调用元数据的一些行$post->the_meta_key
.我想发生这种情况的原因是,还有一些其他的wp魔术在幕后运行$post
在模板文件中可用,但在ajax中不可用。因此,我补充道global $post;
就在我的if
语句,现在它按预期工作。
The question
可以打电话吗global $post;
在ajax的循环中,还是有更好的方法来访问当前的post对象?此外,如果对我的方法有任何通用的最佳实践建议,请让我知道。