Nick
Nick

Reputation: 9

List Featured products and On Sale products without a shortcode in Woocommerce

I understand WooCommerce has provided shortcodes to use for featured and sale products.

However, I can use the shortcode on a page or widget where I want to display them.

What I actually want to do is create a link for sale and one for featured products which will list on sale products and featured products respectively.

Is there anyway I can do that without the shortcode in the way product categories are listed?

Upvotes: 0

Views: 1105

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253919

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.

Upvotes: 3

Related Questions