从产品类别中排除最近查看的产品小部件中的 Woocommerce 产品

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

我想弄清楚如何从 Woocommerce 中最近查看的产品小部件中排除某个类别中的产品。

我知道类别中的产品可以使用以下代码removed/hidden从商店页面

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' );

我想知道如何将 "Machine Category" 中的产品排除在最近查看的产品小部件中。 (我正在使用自动建议商店可用产品的搜索,它允许用户查看存档页面/类别页面中隐藏的产品),所以我想从最近查看的产品小部件中排除这些产品如果用户能够通过搜索访问产品。

我已经使用此代码将类别中的产品排除在搜索结果中之外,这按预期工作正常,但问题是自动建议仍然可以显示查询中的产品 excluded/hidden

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' );

非常感谢有关如何从最近查看的产品小部件中排除查看的产品的帮助。

你需要使用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;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。