How can I get wordpress pagination working with this ajax posts per page filter?

I have created a dynamic filter using ajax that loads content on a page based on a user selected option for the number of posts. This is working. The issue I’m having is trying to come up with a way to also use pagination with the posts that are returned.

functions.php

add_action(‘wp_ajax_myfilter’, ‘psc_tax_filter’);
add_action(‘wp_ajax_nopriv_myfilter’, ‘psc_tax_filter’);

function psc_tax_filter(){
if( isset( $_POST[‘ppp’] ) )
$paged = ( get_query_var(‘paged’) ) ? get_query_var(‘paged’) : 1;
$args = array(
‘post_type’ => ‘products’,
‘posts_per_page’ => $_POST[‘ppp’],
‘tax_query’ => array(
array(
‘taxonomy’ => ‘product-category’,
‘field’ => ‘slug’,
‘terms’ => $_POST[‘term’]
),
),
);

$query = new WP_Query( $args );

<– LOOP STUFF –>

};

template code

<div id = “sorter”>
<form action=”<?php echo site_url() ?>/wp-admin/admin-ajax.php” method=”POST” id=”tax-filter”>
<label class = “mb-0″>
<select name=”ppp”>
<option value=”1″>Show 1 Per Page</option>
<option value=”2″>Show 2 Per Page</option>
<option value=”3″>Show 3 Per Page</option>
<option value=”-1″>Show All</option>
</select>

<?php //get the post taxonomy term
$obj = get_queried_object(); ?>
<input type=”hidden” name=”term” value=”<?php echo $obj->slug; ?>”>
<input type=”hidden” name=”action” value=”myfilter”>
</form>

<div id=”spinner”><img src=”<?php echo get_stylesheet_directory_uri(); ?>/img/spinner.gif”>
</div>
</div><!– #sorter –>

<div id = “sortedPosts”></div>

javascript

$(‘#tax-filter’).change(function() {
var filter = $(‘#tax-filter’);
$.ajax({
url:filter.attr(‘action’),
data:filter.serialize(),
type:filter.attr(‘method’),
beforeSend:function(xhr){
$(‘#spinner’).toggle();
},
success:function(data){
$(‘#spinner’).toggle();
$(‘#sortedPosts’).html(data);
}
});
return false;
});

Read more here:: How can I get wordpress pagination working with this ajax posts per page filter?

Leave a Reply

Your email address will not be published. Required fields are marked *