How to get cart data as json in woocommerce?

Member

by dedrick , in category: PHP CMS , a month ago

How to get cart data as json in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , a month ago

@dedrick 

To get cart data as a JSON in WooCommerce, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
global $woocommerce;
$cart_data = array();

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $item_id = $values['data']->id;
    
    $cart_data[] = array(
        'product_id' => $item_id,
        'product_name' => $_product->get_title(),
        'quantity' => $values['quantity'],
        'price' => $_product->get_price(),
        'subtotal' => $values['line_total'],
    );
}

header('Content-Type: application/json');
echo json_encode($cart_data);


This code snippet loops through each item in the cart and retrieves the product ID, product name, quantity, price, and subtotal for each item. It then encodes this data as JSON and outputs it. You can place this code in a custom plugin or in your theme's functions.php file to get the cart data as a JSON response.