Hide a specific Woocommerce products from loop if they are in cart

爱⌒轻易说出口 提交于 2019-12-09 08:09:21

The following code will remove a specific defined products from Woocommerce shop and archive pages when they are in cart, using this dedicated Woocommerce action hook:

add_action( 'woocommerce_product_query', 'hide_specific_products_from_shop', 20, 2 );
function hide_specific_products_from_shop( $q, $query ) {
    if( is_admin() && WC()->cart->is_empty() )
        return;

    // HERE Set the product IDs in the array
    $targeted_ids = array( 6121, 6107, 14202, 14203 );

    $products_in_cart = array();

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        if( in_array( $cart_item['product_id'], $targeted_ids ) ){
            // When any defined product is found we add it to an array
            $products_in_cart[] = $cart_item['product_id'];
        }
    }
    // We remove the matched products from woocommerce lopp
    if( count( $products_in_cart ) > 0){
        $q->set( 'post__not_in', $products_in_cart );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!