php - 获取 AJAX 请求的初始帖子类型
问题描述
在 WordPress 中,我有一个加载更多按钮,它发出 AJAX 请求以获取更多帖子。这通过检测按钮上的单击事件,然后向运行查询的 PHP 脚本发出请求(如$query = new WP_Query();
.
我想对几种不同的帖子类型使用相同的功能,将帖子类型公开给我的 AJAX 功能的最佳方式是什么?
$.ajax({
type: "POST",
dataType: "json",
url: ajax_get_posts_object.ajax_url,
data: {
action: "ajax_get_posts",
security: ajax_get_posts_object.ajax_nonce,
current_page: next_page,
categories: $selectedCategories,
tags: $selectedTags,
},
beforeSend: function(xhr) {
load_more.text("Fetching...");
},
success: function(response) {
if (response) {
console.log(response);
// An array to store new items added via AJAX
var new_items = [];
// Run through JSON
$.each(response.posts, function(key, value) {
var $new_item = $(`<div class="grid-item article-post-card ${value.category["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}">
<a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
<div class="article-post-card__featured-image-container">
<div class="article-post-card__overlay"></div>
<div class="article-post-card__featured-image">${value.thumbnail}</div>
<div class="article-post-card__category-label">${value.category["name"]}</div>
</div>
<div class="article-post-card__content-wrapper">
<div class="article-post-card__publish-date">
<time class="updated" datetime="${value.post_time}">${value.date}</time>
</div>
<div class="article-post-card__title">${value.title}</div>
<div class="article-post-card__excerpt">${value.introduction}</div>
</div>
</a>
</div>`);
new_items.push($new_item[0]);
});
next_page >= response.pages ? disableLoadMore(true) : disableLoadMore(false);
rebuildGrid($grid, new_items, '*');
updateFilterCount(response.post_count);
// Update boolean so that page count is not reset
load_more_has_run = true;
next_page++;
// If the AJAX function returned no data
} else {
load_more.remove();
}
},
error: function(xhr, status, error) {
console.log("There was an error", error);
}
});
});
解决方案
您可以简单地在data:{}
对象中添加一个post_type
元素
$.ajax({
type: "POST",
dataType: "json",
url: ajax_get_posts_object.ajax_url,
data: {
action: "ajax_get_posts",
security: ajax_get_posts_object.ajax_nonce,
current_page: next_page,
categories: $selectedCategories,
tags: $selectedTags,
post_type: 'your_post_type'
},
...
});
然后在你的 WP_Query() 中使用它
$post_type = key_exists('post_type', $_POST) ? $_POST['post_type'] : 'post';
$query = new WP_Query(
'post_type' => $_POST['post_type'],
...
);
推荐阅读
- java - 我应该如何从我的数据库中获取所有消息并返回它
- javascript - fs 不下载图像
- php - 获取 Array 数据(序列化数据?)并显示,这段代码运行良好,但是为什么,它是否正确?
- c - 关于涉及 scanf() 的简单 C 程序的错误
- azure - 无法删除已禁用的订阅
- php - 致命错误:未捕获的错误:C:\xampp\htdocs\tutorial\Online_exam 中未定义的常量“登录”
- python - 从 4 个摄像头创建实时 3D 视频流
- flutter - 如何关闭 Android 模拟器的布局检查器?
- android - 如何从android应用程序导出数据库?使用 ADB run-as 清空数据库结果
- android - 在启动时运行 Android 守护程序