0

In the front end, I have a custom post type archive page with an AJAX Load More button. The loop of the archive page is ordered by date and ASC. I use the same args for the AJAX loop inside a pre_get_posts function.

Inside the pre_get_posts function I use defined('DOING_AJAX') && DOING_AJAX to detect when there is an AJAX call and apply the order filter.

Also, I would like to add to the conditional statement if it's the custom post type archive page 'workshop'. Unfortunately it doesn't work.

The pre_get_posts function:

add_action('pre_get_posts', 'ajax_filter_posts');
add_filter('ajax_pre_get_posts', 'ajax_filter_posts');
function ajax_filter_posts($query) {
    if ( is_post_type_archive('workshop') && defined('DOING_AJAX') && DOING_AJAX ) {
            $query->set( 'orderby', 'date' );
            $query->set( 'order', 'ASC' );
      $query->set( 'suppress_filters', true );
    }

    return $query;
}

The code for the AJAX Load More button:

function mysite_loadmore_ajax_handler_workshop(){
    $args = json_decode( stripslashes( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1;
    $args['post_type'] = 'workshop';
    $args['post_status'] = 'publish';
    $args['posts_per_page'] = 10;

    $query_ajax = apply_filters('ajax_pre_get_posts', (new WP_Query($args)));

    if ( $query_ajax->have_posts() ) : while ( $query_ajax->have_posts() ) : $query_ajax->the_post();

        get_template_part( 'template-parts/content', 'archive-workshop' );

    endwhile;

    endif;
    die;
}
add_action('wp_ajax_loadworkshop', 'mysite_loadmore_ajax_handler_workshop'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadworkshop', 'mysite_loadmore_ajax_handler_workshop'); // wp_ajax_nopriv_{action}

Any help would be much appreciated, thank you.

1 Answer 1

0

Unless you pass through that information that it's on that archive page there is no way for the request handling the AJAX response to know.

Remember that every new request to the server is a blank slate, there's no shared context that follows the page from the initial request to the AJAX requests unless you explicitly create it and pass it along yourself via cookies, POST parameters, GET parameters, user meta, etc

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.