$attribute_value ) { // Output the variation attribute values (e.g., "Large / black"). $variant_title .= $attribute_value . ' / '; } // remove the last ' / '. return rtrim( $variant_title, ' / ' ); } /** * Get the WooCommerce cart. * * @param \WC_Cart $cart The WooCommerce cart. * @param string $currency The currency. * @return void */ function aict_get_cart( \WC_Cart $cart, string $currency ): void { $response = new stdClass(); $response->currency = $currency; $response->total = aict_get_numeric_value_from_string( $cart->get_cart_contents_total() ); $response->subtotal = aict_get_numeric_value_from_string( $cart->get_subtotal() ); $response->items = array(); $items = $cart->get_cart_contents(); $product_ids = array(); foreach ( $items as $item ) { // Validate that item is an array and has all required keys. if ( ! is_array( $item ) || ! isset( $item['product_id'], $item['line_subtotal'], $item['line_total'], $item['quantity'] ) ) { continue; } $product_ids[] = $item['product_id']; } $products = \wc_get_products( array( 'include' => $product_ids, ) ); foreach ( $items as $item ) { // Validate that item is an array and has all required keys. if ( ! is_array( $item ) || ! isset( $item['product_id'], $item['line_subtotal'], $item['line_total'], $item['quantity'] ) ) { continue; } $item_product_id = $item['product_id']; $product_index = array_search( $item_product_id, array_map( function ( $product ) { return $product->get_id(); }, $products ), true ); // Skip if product not found in the products array. if ( false === $product_index || ! isset( $products[ $product_index ] ) ) { continue; } $product = $products[ $product_index ]; $subtotal = $item['line_subtotal']; $value = $item['line_total']; $discount = $subtotal - $value; // Safely get variation data with fallback. $variation = $item['variation'] ?? array(); $variation_id = $item['variation_id'] ?? 0; $response->items[] = array( 'id' => $item_product_id, 'thumbnailUrl' => get_the_post_thumbnail_url( $product->get_id(), 'shop_thumbnail' ), 'title' => $product->get_name(), 'variantTitle' => aict_get_variant_title( $variation ), 'variantId' => $variation_id, 'discounts' => array( array( 'amount' => $discount, ), ), 'qty' => $item['quantity'], 'value' => $value, 'productPreviewUrl' => $product->get_permalink(), 'sku' => $product->get_sku(), ); } wp_send_json_success( $response ); } /** * Refresh cart action for CI. * * @return void */ function aict_refresh_cart_action(): void { $woocommerce = WC(); $cart = $woocommerce->cart; aict_get_cart( $cart, get_woocommerce_currency() ); }