首页 文章

从Woocommerce中的商店页面中排除产品类别

提问于
浏览
1

我试图隐藏产品类别菜单中的产品类别 .

add_filter( 'woocommerce_product_categories_widget_args', __NAMESPACE__ . '\\rv_exclude_wc_widget_categories' );
    function rv_exclude_wc_widget_categories( $cat_args ) {
        $cat_args['exclude'] = array('129'); // Insert the product category IDs you wish to exclude
        $includes = explode(',', $cat_args['include']); 
        $cat_args['include'] = array_diff($includes,$cat_args['exclude']);
        return $cat_args;
    }

function exclude_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-1, -129' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

我的代码的顶级功能在实际属于某个类别时成功隐藏了我的菜单中的类别 . 但是,它不会将其隐藏在主商店页面中 . 这是我正在尝试使用底部代码,但是,这似乎没有做任何事情 .

关于如何做到这一点的任何想法?代码放在我的functions.php文件中 .

编辑:试图澄清我在问什么 .

首次打开我的产品页面时,我现在在菜单中隐藏了类别“TEST”,如下所示 .

enter image description here

但是,当我点击产品或类别时,菜单会返回到如下所示的位置 .

enter image description here

1 回答

  • 2

    对于您的第一个功能(从小部件隐藏特定产品类别):

    add_filter( 'woocommerce_product_categories_widget_args', 'exclude_product_categories_widget', 10, 1 );
    function exclude_product_categories_widget( $list_args ) {
        $categories = array('129');
    
        if(isset( $list_args['include'])):
            $included_ids =  explode( ',', $list_args['include'] );
            $included_ids = array_unique( $included_ids );
            $included_ids = array_diff ( $included_ids, $categories );
    
            $list_args['include'] = implode( ',', $included_ids);
        else:
            $list_args['exclude'] = $categories;
        endif;
    
        return $list_args;
    }
    

    要在商店和存档页面中的产品类别(术语ID) 129 下排除您的产品,请使用以下专用的Woocommerce挂钩功能:

    add_filter('woocommerce_product_query_tax_query', 'exclude_product_category_in_tax_query', 10, 2 );
    function exclude_product_category_in_tax_query( $tax_query, $query ) {
        if( is_admin() ) return $tax_query;
    
        // HERE Define your product categories Terms IDs to be excluded
        $terms = array( 129 ); // Term IDs
    
        // The taxonomy for Product Categories custom taxonomy
        $taxonomy = 'product_cat';
    
        $tax_query[] = array(
            'taxonomy' => $taxonomy,
            'field'    => 'term_id', // Or 'slug' or 'name'
            'terms'    => $terms,
            'operator' => 'NOT IN', // Excluded
            'include_children' => true // (default is true)
        );
    
        return $tax_query;
    }
    

    代码位于活动子主题(或主题)的function.php文件中 . 经过测试和工作 .

相关问题