2

I have a custom Wordpress widget which allows the user to filter products via attributes (custom taxonomies).

It all happens via an Ajax call, but I'm having trouble keeping the pagination up to date based on the filtered results.

For example:

If the page loads 30 products, 10 to a page = 3 pages of results.

The user then filters by an attribute which reduces that 30 products to 20. I need the pagination to change to just 2 pages of results.

Here's a sample of the WP_Query that replaces the default page content. You can see the woocommerce_pagination() which doesn't appear to work in this environment.

// Args
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 10,
    'orderby' => 'name',
    'order' => 'ASC',
    'tax_query' => $tax_query
);

$query = new WP_Query( $args );

if( $query->have_posts() ) :
    woocommerce_product_loop_start();
    while( $query->have_posts() ): $query->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
    woocommerce_product_loop_end();

    // TODO - get pagination working
    woocommerce_pagination();

    wp_reset_postdata();
else :
    echo '<p>No products found</p>';
endif;
gurtfrobe
  • 316
  • 6
  • 17

1 Answers1

2

WooCommerce pagination works based on global $wp_query variable. But you are using your own $query variable. That's why it is obvious why it is not working.

You have 2 ways to go:

  1. First is using query_posts instead of WP_QUERY class.
  2. The second way is a small hack, where you can cheat $wp_query pagination argument.

Here it is:

 global $wp_query;
  $wp_query->max_num_pages=$query->max_num_pages;
  // TODO - get pagination working
  woocommerce_pagination();
Mr.Senhaji
  • 395
  • 5
  • 13
Elvin Haci
  • 3,503
  • 1
  • 17
  • 22
  • Thanks for the help! I tried the `$wp_query` cheat which got me most of the way there. What's happening now is the URL of the pagination buttons are set to `/wp-admin/admin-ajax.php?paged=2` The form `action` attribute is set to `= site_url() ?>/wp-admin/admin-ajax.php` – gurtfrobe Jun 20 '18 at 01:33
  • I was able to solve the pagination URL issue with step 2 of [this post](https://stackoverflow.com/questions/20150653/wordpress-pagination-not-working-with-ajax). Though as is always the way a new obstacle has arisen... my filters are wiped when reloading the page when clicking on the pagination. That's a task for another day. I'll accept _Elvin Haci_'s answer! – gurtfrobe Jun 20 '18 at 02:45