Khorshed Alam Khorshed Alam - 1 year ago 129
PHP Question

WooCommerce Recover Cart from Session Data

I'm working for a tiny Abandon Cart Recovery Plugin and I need to recover the cart from


Here is the unserialiezed cart data for 1 variable product in cart.

array (size=1)
'cart' =>
array (size=9)
'product_id' => int 22
'variation_id' => int 24
'variation' =>
array (size=1)
'attribute_pa_color' => string 'green' (length=5)
'quantity' => int 1
'line_total' => float 20
'line_tax' => int 0
'line_subtotal' => int 20
'line_subtotal_tax' => int 0
'line_tax_data' =>
array (size=2)
'total' =>
array (size=0)
'subtotal' =>
array (size=0)

I'm trying to recover the whole cart with this data. I know it's possible to to loop through this array and add items to cart via

WC_Cart::add_to_cart( $product_id, $quantity, $variation_id, $variation );

But is there any more elegant way to do it as the data is stored in
table and totally WooCommerce compatible ?

Answer Source

I didn't find any other solution regarding this, so just cleared the cart first and then gone through a loop with the cart data and added the items to cart programmatically. Here is the code looks like.

if ( $cart_data ) {

    foreach ( $cart_data as $product ) {

        // Validate Product data
        $product_id   = isset( $product['product_id'] )    ? (int) $product['product_id']   : 0;
        $quantity     = isset( $product['quantity'] )      ? (int) $product['quantity']     : 1;
        $variation_id = isset( $product['variation_id'] )  ? (int) $product['variation_id'] : 0;
        $variation    = isset( $product['variation'] )     ? $product['variation']          : array();

        WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download