Search code examples
wordpresswoocommercecartproduct-variations

WooCommerce: Get a key=>value array of a cart items variations


This is a self Q&A

I need a way to neatly build a key=>value array of all the variations for an item in a cart. The available Woo functions all return a string.


Solution

  • This function takes a cart item, and returns a key=>value array.

    Place it in functions.php

    /*
     * Get a cart product/item's variation as a key=>value pair
     */
        function store_get_cart_product_variations($cart_item) {
            $variations = WC()->cart->get_item_data($cart_item, true); 
    
            // Explode and trim
            $parts = explode(PHP_EOL, $variations);
            $parts = array_filter($parts);
    
            // Build a key=>value pair, trim any extra whitespace
            $variations = array();
            foreach($parts as $part) {
                list($key, $value) = explode(':', $part);
                $variations[trim($key)] = trim($value);
            }
    
            return $variations;
        }
    

    And then it can be used like this:

    $cart_items = WC()->cart->get_cart();
    foreach ( $cart_items as $cart_item_key => $cart_item ) {
        $variations = store_get_cart_product_variations($cart_item);        
        foreach($variations as $type => $value) {
            echo $type . ': ' . '<span class="value">' . $value .'</span>';
        }
    }