olim
olim

Reputation: 73

Woocommerce Products Widget for a specific category

How can I make the Woocommerce Products Widget display Products of a specific Category only? Current options are on-sale, featured, and all.

Upvotes: 0

Views: 3647

Answers (2)

rkoms
rkoms

Reputation: 41

To show products from current category, something like this works:

add_filter( 'woocommerce_products_widget_query_args', function( $query_args ){
    $category = get_queried_object();
    $cat_slug = $category->slug;
    $query_args['tax_query'] = array( array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $cat_slug,
    ));

    return $query_args;
}, 10, 1 );

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253921

This can be done with a custom function hooked in woocommerce_products_widget_query_args filter hook. You will have to set inside it, in the array, your product category (or your product categories if more than one).

Here is the code:

add_filter( 'woocommerce_products_widget_query_args', function( $query_args ){
    // Set HERE your product category slugs 
    $categories = array( 'music', 'posters' );

    $query_args['tax_query'] = array( array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $categories,
    ));

    return $query_args;
}, 10, 1 );

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested in WooCommerce 3+ and works

Upvotes: 3

Related Questions