Kolawole Emmanuel Izzy
Kolawole Emmanuel Izzy

Reputation: 1052

Exclude Woocommerce products in recently viewed products widget from a product category

I'm trying to figure out how to exclude product in a category from Recently Viewed Product Widget in Woocommerce.

I know products in a category can be removed/hidden from shop page using the below code

function custom_pre_get_posts_query( $q ) {
    $tax_query = (array) $q->get( 'tax_query' );
    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'machine' ), // Don't display products in the machine category on the shop page.
           'operator' => 'NOT IN'
    );
    $q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

I will like to know how to exclude products in "Machine Category" from showing up in recently viewed product widget. (i'm using a search which auto-suggest products available on the store and it allows users to view product that are hidden from the archive page / category page), so i'd like to exclude the products from the recently viewed product widget if a user was able to access the product through the search.

I have used this code to exclude product in a category from displaying in search results, which works fine as expected but the issue is the auto suggestions which can still display product excluded/hidden from queries

function hello_pre_get_posts( $query ) {
   if ( $query->is_search() ) {
       $query->set( 'post_type', array( 'product' ) );
       $tax_query = array( array(
               'taxonomy' => 'product_cat',
               'field'   => 'slug',
               'terms'   => 'machine',
               'operator' => 'NOT IN',
           ),
       );
       $query->set( 'tax_query', $tax_query );
    }
}
add_action( 'pre_get_posts', 'hello_pre_get_posts' );

Assistance on how to exclude viewed product from Recently Viewed Products Widget will be highly appreciated.

Upvotes: 3

Views: 1381

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254483

You need to use woocommerce_recently_viewed_products_widget_query_args dedicated filter hook:

// Exclude products in recently viewed products widget from "machine" product category
add_filter( 'woocommerce_recently_viewed_products_widget_query_args', 'custom_recently_viewed_products_widget_query_args', 10, 1 );
function custom_recently_viewed_products_widget_query_args( $args ) {

    $args['tax_query'][] = array(
           'taxonomy' => 'product_cat',
           'field'    => 'slug',
           'terms'    => array( 'machine' ), 
           'operator' => 'NOT IN', 
    );

    return $args;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 4

Related Questions