OK, so first of all – AJAX requests are separate, so you don’t have to remove_action
if you haven’t added it earlier…
And to be honest, I don’t really get your code – you modify the global wp_query
object, but it’s really not so clear how and why is there any query created during AJAX call – WP processes these requests in a different way… Saying this, here’s the code that should work… (it doesn’t need any changes in your JS, so I’m posting only PHP code)
function ajax_sortposts() {
$sorting_order = $_POST['sorting_order'];
// we don't use any global $wp_query, since no global $wp_query is created during AJAX calls
// instead we create our own WP_Query instance - so we don't need to use pre_get_posts
$posts_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page', get_option('posts_per_page'),
'paged' => 1,
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'tag__not_in' => array(14),
'order' => 'DESC',
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '130 days ago',
)
)
) );
if ( 'MostViewed' == $sorting_order ) {
$posts_query['meta_key'] = 'link_click_counter';
$posts_query['orderby'] = 'meta_value_num';
}
get_content( $posts_query );
die;
}
function get_content ( $query ) {
// again we shouldn't use global $wp_query in here
// and certainly we SHOULDN'T call wp() function at all...
?>
<div id="post-wrapper" class="grid-wrapper">
<?php
if ( $query->have_posts() ) :
echo '<div class="gallery-wrapper">';
while ( $query->have_posts() ) : $query->the_post();
if ( 'one-column' === get_option( 'baseline_customizer_post_style', 'one-column' ) ) {
get_template_part( 'template-parts/content' );
} else {
get_template_part( 'template-parts/content-grid-item' );
}
endwhile;
echo '</div>';
else :
get_template_part( 'template-parts/content-none' );
endif;
if ( $query->max_num_pages > 1 )
echo '<div class="loadmore_posts">More posts</div>';
?>
</div>
<?php
}