Support » Fixing WordPress » How to use multiple custom WP_query called with Ajax

  • I’m having an issue working with multiple custom WP_Query’s. Basically I have a set WP_Query that I use for my homepage that you can replace with a different custom WP_Query using ajax along with multiple others. I’m not positive but I think the use of global $WP_query is causing issues with pagination because the next post links are showing random duplicate posts. So I’m looking for some advice on the right way to do what I’m doing to get the proper output.

    So I start with my homepage loop.

    `<?php
    global $post;
    $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
    $args = array(
    ‘meta_key’ => ‘hotness’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    ‘cat’ => -1,
    ‘posts_per_page’ => 4,
    ‘paged’ => $paged
    );
    $main_query = new WP_Query( $args );
    while ( $main_query->have_posts() ) : $main_query->the_post(); ?>
    <——SOME CONTENT——>
    <?php endwhile; ?>

    <?php if ( $main_query->max_num_pages > 1 ) : ?>
    <div class=”infinitescroll”>
    <?php next_posts_link( __( ‘Load more posts’ ) ); ?>
    </div>
    <?php endif; ?>`

    Then when a tab is clicked I empty the main loop from it’s container using jquery and trigger this function. I’m thinking the new loop needs a different custom query variable but using one prevents wordpress functions from working in the new loop.

    `add_action(‘wp_ajax_loop_new’, ‘loop_new’);
    add_action(‘wp_ajax_nopriv_loop_new’, ‘loop_new’);
    function loop_new(){
    wp_reset_query();// Added this but didn’t help.
    global $wp_query;
    $paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
    $args = array(
    ‘cat’ => -1,
    ‘posts_per_page’ => 16,
    ‘paged’ => $paged
    );
    $wp_query = new WP_Query( $args );//feel like I need to use another variable other than $wp_query but that prevents wordpress functions from working in the loop.

    get_template_part( ‘loop-new’ );

    exit;
    }`

    And then I call a new loop using a manual link to page 2 of the loop that I use for non javascript users and it also triggers infinite scroll. But page two brings a few duplicate posts.

    `<?php
    while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
    <—-SOME CONTENT—->
    <?php endwhile; ?>

    <?php if ( $wp_query->max_num_pages > 1 ) : ?>
    <div class=”infinitescroll”>
    <a href=”http://mysite.com/page/2″>Load more posts</a>
    </div>
    <?php endif; ?>`

  • The topic ‘How to use multiple custom WP_query called with Ajax’ is closed to new replies.