WooCommerce: Check if items are already in cart

后端 未结 4 1863
无人共我
无人共我 2020-12-09 00:07

I found this great snippet from this website

The following is the function to check if a specific product exists in cart:

        function woo_in_ca         


        
4条回答
  •  悲&欢浪女
    2020-12-09 00:40

    global $woocommerce and $woocommerce->cart is outdated and simply replaced by WC()->cart

    Here is a custom function with an argument that accepts a unique integer product ID or an array of product IDs, and that will return the number of matched Ids that are in cart.

    The code handle any product type, including variable product and product variations:

    function matched_cart_items( $search_products ) {
        $count = 0; // Initializing
    
        if ( ! WC()->cart->is_empty() ) {
            // Loop though cart items
            foreach(WC()->cart->get_cart() as $cart_item ) {
                // Handling also variable products and their products variations
                $cart_item_ids = array($cart_item['product_id'], $cart_item['variation_id']);
    
                // Handle a simple product Id (int or string) or an array of product Ids 
                if( ( is_array($search_products) && array_intersect($search_products, cart_item_ids) ) 
                || ( !is_array($search_products) && in_array($search_products, $cart_item_ids)
                    $count++; // incrementing items count
            }
        }
        return $count; // returning matched items count 
    }
    

    This code goes in function.php file of your active child theme (active theme or in any plugin file).

    Code is tested and works.


    USAGE:

    1) For a unique product ID (integer):

    $product_id = 102;
    
    // Usage as a condition in an if statement
    if( 0 < matched_cart_items($product_id) ){
        echo '

    There is "'. matched_cart_items($product_id) .'"matched items in cart


    '; } else { echo '

    NO matched items in cart


    '; }

    2) For an array of product IDs:

    $product_ids = array(102,107,118);
    
    // Usage as a condition in an if statement
    if( 0 < matched_cart_items($product_ids) ){
        echo '

    There is "'. matched_cart_items($product_ids) .'"matched items in cart


    '; } else { echo '

    NO matched items in cart


    '; }

    3) For an array of product IDs for 3 or more matched cart items for example:

    $product_ids = array(102, 107, 118, 124, 137);
    
    // Usage as a condition in an if statement (for 3 matched items or more)
    if( 3 <= matched_cart_items($product_ids) ){
        echo '

    There is "'. matched_cart_items($product_ids) .'"matched items in cart


    '; } else { echo '

    NO matched items in cart


    '; }

提交回复
热议问题