0
votes

I want to conditionally hide a group of Woocommerce products on a category page depending on the current shopping cart contents. I have a category called boxes with four products. Two of them are also in the cardboard category and two are in the plastic category.

If product with ID 23 is in the cart already, I want to show plastic boxes. If it isn't, I want to hide them. I know how to check the cart contents, but once I have that answer, how do I hide products from the plastic category from that page?

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

1 Answers

4
votes

The hook which you are using right now, is triggerred after products are fetch from database. You can filter the products from the query itself. In below code, you can pass products which you want to hide on front end.

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