0

I am trying to make post filter.

Here is index.php

<?php

$args = array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => get_option( 'posts_per_page' ),
    'order'          => 'DESC',
);

$args[ 'category__in' ] = array(1, 2, 3);

$searchPosts = new WP_Query( $args );

$postCount = $searchPosts->post_count;

if( $searchPosts->have_posts() ) :

    while( $searchPosts->have_posts() ) :

        $searchPosts->the_post();

            get_template_part( 'template-parts/content', 'main-feed' );

    endwhile;

else :

    get_template_part( 'template-parts/content', 'none' );

endif;

$vars = $searchPosts->query_vars;

?>

<script>
    var postsMain = '<?php echo json_encode( $vars ) ?>',
        currentPageMain = <?php echo $vars[ 'paged' ] ?>,
        maxPageMain = <?php echo $searchPosts->max_num_pages; ?>
</script>

Here is ajax.js

$('.call-post').click(function () {

    var button = $(this),
        data = {
            'action': 'ajaxLoadMore',
            'query': postsMain,
            'page': currentPageMain,
        };

    $.ajax({
        url: ajaxUrl,
        data: data,
        type: 'POST',
        beforeSend: function (xhr) {
            //
        },
        success: function (data) {
            if (data) {
                $('.main-posts').append(data);
                currentPageMain++;
            } else {
                button.remove();
            }
        }
    });
});

It is my ajax handler function.

function ajaxLoadMore() {
    $args = json_decode( stripslashes( $_POST[ 'query' ] ), true );

    $args[ 'paged' ] = $_POST[ 'page' ] + 2;
    $args[ 'post_status' ] = 'publish';

    $ajaxPosts = new WP_Query( $args );

    if( $ajaxPosts->have_posts() ) {
        while( $ajaxPosts->have_posts() ) {
            $ajaxPosts->the_post();
            get_template_part( 'template-parts/content', 'main-feed' );
        }
    }

    exit;
}

It looks like good, but i calls only first category posts.

  • What is the postsMain var that you are passing to your callback? Show a var_dump() or something. – Michael Sep 28 '18 at 23:32
  • It shows true category__in ids. And it shows true posts without pagination. Problem is ajax. It not calls true. – bilimokur Sep 29 '18 at 6:31
  • 4 months... and i don't find solution. – bilimokur Feb 10 at 16:29
  • Why are you json decoding POST data? – Michael Feb 11 at 17:16
  • Because it sends jsoned data. I need normal array for query. – bilimokur Feb 12 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.