我正在尝试通过 AJAX 将数组传递到外部 php 文件。它是要从查询中排除的帖子 ID 的硬编码列表。
这是我在数组中设置帖子 ID 的位置,这些 ID 存在于数据库中。然后,我将变量 $postsNotIn
作为内爆数组传递给 JS 文件,以传递给 ajax.php
问题是,它不起作用。我认为 $postNotIn
不会作为数组传递,因为 post__not_in
需要一个数组。
我尝试传递 $features
但也不起作用。
我不断收到 0
作为响应。
但是,当我在查询中对数组进行硬编码时 'post__not_in' => array(230, 280, 268);
它工作正常。
如何将 ID 以正确的数组形式传递给 ajax.php
?
编辑 如果我将 $exclude
包装在 array()
中,就像这样 'post__not_in' => array($exclude)
它仅排除第一个帖子 ID,而忽略其余 2 个。
HTML 按钮
$features = array(320, 280, 268); // Array of posts to exclude
$postsNotIn = implode(", ", $features);
<a class="btn btn-lg btn-default load-more-button"
data-exclude="<?php echo $postsNotIn; ?>"
data-page="1"
data-url="<?php echo admin_url('admin-ajax.php'); ?>">
Load More
</a>
Javascript
$('.load-more-button:not(.loading)').on('click', function() {
var that = $(this);
var ajaxurl = that.data('url');
var page = that.data('page');
var exclude = that.data('exclude');
$.ajax({
url: ajaxurl,
type: 'post',
data: {
page: page,
exclude: exclude,
action: 'load_more'
},
error: function(response) {
console.log(response);
},
success: function(response) {
console.log(response);
}
这是外部ajax.php
文件
function load_more() {
$paged = $_POST['page'] + 1;
$exclude = $_POST['exclude'];
$query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged,
'post__not_in' => $exclude
));
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
else :
echo 0;
endif;
wp_reset_postdata();
die();
最佳答案
post__not_in
需要一个 ID 数组,而您传入的是逗号分隔的字符串。
您需要反转将数组转换为字符串以在属性中使用时运行的过程。
// Before using the $exclude variable, convert the string to an array
$exclude = array_map( 'trim', explode( ',', $exclude ) );
根据我们在评论部分的讨论,我删除了分隔符中的空格。 AJAX 回调接收到的字符串没有任何空格。
我对数组中的所有元素使用 trim()
来处理任何包含空格的 ID。
关于javascript - 使用 post__not_in 中的外部数组排除 WordPress 查询中的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43462414/