C
C
castetus2021-03-19 12:09:56
WordPress
castetus, 2021-03-19 12:09:56

Woocommerce - how to combine product filter and pagination?

Hello everyone!
I made a filter for products in a category, a simple one:

add_action( 'pre_get_posts', 'custom_products_filter' );
function custom_products_filter( $query ) {
  if (!is_product_category() || is_admin()){
    return;
  }

  if (isset($_GET['weight']) && $query->is_main_query()){
    $args = ['numberposts' => -1, 'weight' => $_GET['weight']];
    $products = wc_get_products($args);
    foreach ($products as $product){
      $ids[] = $product->get_id();
    }
    $query->set('post__in', $ids);
  }
}

But if you filter products not on the first page of the category, then the pagination value is saved - and the filtered products may not be enough to display on a page other than the first.
That is, the url looks like /product-category/govyadina/page/2/?weight%5B0%5D=0.1
I see the correct algorithm as follows:
if the current page is not the first page when applying the filter, then the pagination is reset to the beginning, and the filter is already applied there. That is, "page/2/" should be removed from the url. (and everything after ? leave)
And how to do it? Manually cut out the pagination parameter from the url and redirect?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question