2017-06-23 231 views
0

我想根据当前的购物车内容在分类页面上有条件地隐藏一组Woocommerce产品。我有一个类别叫四个产品箱。其中两个也在纸板类别,两个在塑料类别。以编程方式隐藏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

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

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

This Works,thank you。 – poptartgun

相关问题