The following code will filter products from woocommerce product query to:
- Display featured products using
https://www.example.com/shop/?featured=1
query string
- Display on sale products using
https://www.example.com/shop/?onsale=1
query string
The code:
// Featured products
add_filter( 'woocommerce_product_query_tax_query', 'filter_featured_products', 20, 1 );
function filter_featured_products( $tax_query ){
if( isset($_GET['featured']) && $_GET['featured'] ){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name', // name or term_id
'terms' => array('featured')
);
}
return $tax_query;
}
// On sale products
add_filter( 'woocommerce_product_query_meta_query', 'filter_on_sale_products', 20, 1 );
function filter_on_sale_products( $meta_query ){
if( isset($_GET['onsale']) && $_GET['onsale'] ){
$meta_query[] = array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>'
);
}
return $meta_query;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.