首页 文章

以编程方式隐藏Woocommerce产品

提问于
浏览
0

我想在类别页面上有条件地隐藏一组Woocommerce产品,具体取决于当前的购物车内容 . 我有一个名为盒子的类别,有四种产品 . 其中两个也属于纸板类,两个属于塑料类 .

如果ID为23的产品已经在购物车中,我想展示塑料盒 . 如果不是,我想隐藏它们 . 我知道如何查看购物车内容,但是一旦我得到了答案,我如何从该页面隐藏塑料类别的产品?

add_action( 'woocommerce_before_shop_loop', 'my_before_shop_loop' );

function my_before_shop_loop() {
    global $woocommerce;

    $flag = 0;

    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];

        if ($_product->id == '23') {
            $flag = 1;
        }
    }

    if ($flag == 0) {

        // hide products that are in the plastic category
        // this is where I need help

    }
}

1 回答

  • 2

    您正在使用的钩子在从数据库获取产品后触发 . 您可以从查询本身过滤产品 . 在下面的代码中,您可以传递要隐藏在前端的产品 .

    function custom_pre_get_posts_query( $q ) {
    
            // Do your cart logic here
    
            // Get ids of products which you want to hide
            $array_of_product_id = array();
    
            $q->set( 'post__not_in', $array_of_product_id );
    
        }
        add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );
    

相关问题