Exclude posts in WordPress Query with an external array in post__not_in

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?

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-url="<?php echo admin_url('admin-ajax.php'); ?>">
    Load More

The Javascript

$('.load-more-button:not(.loading)').on('click', function() {
    var that = $(this);
    var page = that.data('page');
    var exclude = that.data('exclude');

            url: ajaxurl,
            type: 'post',
            data: {
                page: page,
                exclude: exclude,
                action: 'load_more'
            error: function(response) {
            success: function(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() );
else :
    echo 0;



Read more here: Exclude posts in WordPress Query with an external array in post__not_in

Leave a Reply

Your email address will not be published. Required fields are marked *