0

I have a php script from WooCommerce that is trying to retrieving the active cart information per user session id.

I need to know in WooCommerce where this data is stored and generated.

Basically my main goal is to retrieve the active cart content and return them as php variables.

Any way to do this?

Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97

1 Answers1

1

You can get the active cart information through WC()->cart->get_cart(); and the product count by WC()->cart->get_cart_contents_count();

Full cart info

foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
    $product_id = $cart_item['product_id']; // Product ID
    $product_obj = wc_get_product($product_id); // Product Object
    $product_qty = $cart_item['quantity']; // Product quantity
    $product_price = $cart_item['data']->price; // Product price
    $product_total_stock = $cart_item['data']->total_stock; // Product stock
    $product_type = $cart_item['data']->product_type; // Product type
    $product_name = $cart_item['data']->post->post_title; // Product Title (Name)
    $product_slug = $cart_item['data']->post->post_name; // Product Slug
    $product_description = $cart_item['data']->post->post_content; // Product description
    $product_excerpt = $cart_item['data']->post->post_excerpt; // Product short description
    $product_post_type = $cart_item['data']->post->post_type; // Product post type

    $cart_line_total = $cart_item['line_total']; // Cart item line total
    $cart_line_tax = $cart_item['line_tax']; // Cart item line tax total
    $cart_line_subtotal = $cart_item['line_subtotal']; // Cart item line subtotal
    $cart_line_subtotal_tax = $cart_item['line_subtotal_tax']; // Cart item line tax subtotal

    // variable products
    $variation_id = $cart_item['variation_id']; // Product Variation ID
    if($variation_id != 0){
        $product_variation_obj = wc_get_product($variation_id); // Product variation Object
        $variation_array = $cart_item['variation']; // variation attributes + values
    }
}

Reference: https://stackoverflow.com/a/42784920/5019802

Hope this helps!

Community
  • 1
  • 1
Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
  • Hey Thanks fr your reply, Excuse my newbieness but, if i put this text in a php file it seems to be missing a wc() class. am i doing something wrong? where am i supposed to put this snippet in order for me to be able to use the variables globally within any php document on the server? @Raunak Gupta – StarShows Studios Mar 28 '17 at 18:02
  • @StarShowsStudios: are you getting any error? and in which hook you have written the above code? – Raunak Gupta Mar 28 '17 at 18:19