I am trying to pass an array via AJAX to an external php file. It's a hard-coded list of post IDs to be excluded from the query.
This is where I'm setting the post IDs in an array, these IDs exist in the database. Then I'm passing the variable $postsNotIn
as an imploded array to the JS file to be passed over to ajax.php
The problem is, it is not working. I don't think the $postNotIn
is being passed through as an array because post__not_in
is expecting an array.
I tried passing $features
instead but that didn't work either.
I keep getting 0
as a response.
However when I hardcode the array in the query 'post__not_in' => array(230, 280, 268);
it works fine.
How can I pass the IDs in the correct array form to ajax.php
?
EDIT if I wrap $exclude
in array()
like so 'post__not_in' => array($exclude)
it only excludes the first post ID while ignoring the remaining 2.
the HTML button
$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>
The 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);
}
This is the external ajax.php
file
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();