Home » Php » javascript – Passing post__not_in array to ajax in WordPress wp_query

javascript – Passing post__not_in array to ajax in WordPress wp_query

Posted by: admin February 25, 2020 Leave a comment

Questions:

So I’ve looked at other answers to this for a few days now and cannot seem to figure out where I’m going wrong here. My goal is to create a “Load More” button and use Ajax to load more posts in my custom wp_query on my blog page. I two wp_query loops on that page, one for a single post and one for the rest of the posts. I’m using ‘post__not_in’ to exclude the post in the first query from the second query. When I then load more posts via Ajax I get a duplicate post. So I was trying to grab an array of the IDs loaded on the main query and pass that array through to Ajax to exclude those posts from loading when I click to load more posts.

I will also be putting this on my category page. On that page I have three queries set up, one with a single post, one as a sidebar with two posts, and then the primary query which will load more posts with Ajax.

Right now no posts are loading when I click on the “Load More” button. Using WP PHP Debug I can see that my variable for excluding posts is outputting as an array, but it doesn’t appear to be working. I’m not sure where I’m going wrong here.

As of now this is what I have. Here is my template with the two queries and the Ajax button:

<!--- Featured Post --->
<section id="featured" class="blog-content">

    <!-- Starts the loop -->
    <?php
        $postsPerPage = 1;
        $offset = 1;
        $cat_id = get_query_var('cat');
        $args = array(
                'post_type' => 'post',
                'posts_per_page' => $postsPerPage
        );

        $featuredloop = new WP_Query($args);

        while ($featuredloop->have_posts()) : $featuredloop->the_post();

        $ids[] = get_the_ID();
    ?>

    <?php include ('template-parts/blog/featured-post.php'); ?>  

    <!-- Ends the loop -->
    <?php
    endwhile;
    wp_reset_postdata(); ?>

</section><!-- #posts -->

<!--- Posts --->
<section id="posts" class="ajax-posts posts blog-content">

    <!-- Starts the loop -->
    <?php
        $postsPerPage = 6;
        $offset = 1;
        $cat_id = get_query_var('cat');
        $args = array(
                'post_type' => 'post',
                'posts_per_page' => $postsPerPage,
                'post__not_in' => $ids
        );

        $loop = new WP_Query($args);

        while ($loop->have_posts()) : $loop->the_post();

        $skip[] = get_the_ID();

        $exclude = implode(',', $skip);

    ?>

    <?php include ('template-parts/blog/post.php'); ?>

    <!-- Ends the loop -->
    <?php
    endwhile;
    wp_reset_postdata(); ?>

</section><!-- #posts -->

<div class="load-more">

    <div id="more_posts" class="button" data-exclude="<?php echo $exclude; ?>" data-category="<?php echo $cat_id; ?>">Load More</div>

</div>

Here is my Ajax jQuery file:

jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error

    $(document).ready(function(){

        var ppp = 6; // Post per page
        var cat = $('#more_posts').data('category');
        var exclude = $('#more_posts').data('exclude');
        var pageNumber = 1;


        function load_posts(){
            pageNumber++;
            $.ajax({
                type: "POST",
                dataType: "html",
                url: ajax_posts.ajaxurl,
                data: {
                    cat: cat,
                    pageNumber: pageNumber,
                    ppp: ppp,
                    exclude: exclude,
                    action: 'more_post_ajax'
                },
                success: function(data){
                    var $data = $(data);
                    if($data.length){
                        $(".ajax-posts").append($data);
                        $("#more_posts").attr("disabled",false);
                    } else{
                        $("#more_posts").attr("disabled",true);
                        $("#more_posts").replaceWith('<h4>No more posts...</h4>');
                    }
                },
                error : function(jqXHR, textStatus, errorThrown) {
                    $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
                }

            });
            return false;
        }

        $("#more_posts").on("click",function(){ // When btn is pressed.
            $("#more_posts").attr("disabled",true); // Disable the button, temp.
            load_posts();
        });

    });

});

And here is my Ajax function in functions.php

// Ajax Load More Posts
function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 0;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
    $cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
    $exclude = $_POST['exclude'];

    $postNotIn = explode(",", $exclude);

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => $ppp,
        'cat' => $cat,
        'paged' => $page,
        'post__not_in' => $postNotIn,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= get_template_part( 'template-parts/blog/post' );

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Any insights would be amazingly helpful and appreciated.

Thanks!

How to&Answers: