I have multiple custom query vars to filter products with the pre_get_posts hook and the add_query_arg function.
All works fine except the pagination, when i navigate to the page number 5 (for example) without filtering and then i select one filter, if the products for that filter doesn't have 5 pages it will show nothing.
What most sites do is to return to first page when selecting a filter, but i don't know exactly how to do it.
I have this for a start, but of course it doesn't worked. I'll be appreciated if someone helps me.
if ( in_array(get_query_var('brand'), $wp_query->query_vars) ) {
get_query_var('paged') = 1;
}
How i'm filtering:
function custom_query_vars_filter( $custom_vars ) {
$custom_vars[] = 'marca';
return $custom_vars;
}
add_filter( 'query_vars', 'custom_query_vars_filter' );
function customize_main_query( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
if ( is_product_category() ) {
$query->set('posts_per_page', 3);
$marca= get_query_var('marca');
$tax_query = array('relation' => 'AND');
if ( $marca ) {
$tax_query[] = array(
'taxonomy' => 'brands',
'field' => 'slug',
'terms' => $marca
);
}
$query->set( 'tax_query', $tax_query );
}
}
}
add_action( 'pre_get_posts', 'customize_main_query' );
Category archive page
$marca_arg = isset($marca) ? array($marca) : [];
foreach ($marcas_terms as $marca_term) {
<div class="filtro-item">
<a href="<?php echo (in_array($marca_term->slug, $marca_arg)) ?
esc_url(remove_query_arg('marca')) : esc_url(add_query_arg('marca',
"$marca_term->slug")); ?>"><span class="check-
filtro"></span><?php echo $marca_term->name; ?></a>
</div>
}
is_product_category
come from? You should be using the provided$query
object for those checks, stuff like that always references the main query. Also note thatget_query_var('paged') = 1;
makes no sense, it's the same as1 = get_value()
, both are meant to appear on the right of the=