issues woocommerce add_to_cart with data

I have an issue when I’m trying to set a data into my item:

add_filter('woocommerce_add_cart_item_data', '_add_custom_item_data', 10, 2);
add_filter('woocommerce_get_cart_item_from_session', '_get_cart_item_from_session', 10, 2);

function _add_custom_item_data($cart_item_data, $product_id){
    if(!empty($cart_item_data)){
        $cart_item_data['custom_field'] = 'aaaa';
    }
    return $cart_item_data;
}
function _get_cart_item_from_session($cart_item, $values){
    if (isset($values['custom_field'])) {
            $cart_item['custom_field'] = $values['custom_field'];
        }
    return $cart_item;
}

when I use:

Read More
$woocommerce->cart->add_to_cart($id,'1','','',array('_my_data','000000000000000000000000000000'));

the _add_custom_item_data function is executed as well and I have the _my_data variable.

but i’m try to get the variable with my product:

$items = $woocommerce->cart->get_cart();
foreach($items as $item){
    echo $woocommerce->cart->get_item_data( $item ) . "<br>";
}

I didn’t see my variable…

Any idea?

Related posts

Leave a Reply

2 comments

  1. At last function try following to get data

    <?php 
                    $cart = $woocommerce->cart->get_cart();
                    $items = 0;
                    $total = 0;
                    foreach ($cart as $p) {
                        $total += $p['line_total'];
                        $items += $p['quantity'];
                    }
                    echo $items;
                    echo $total;
                ?>
    
  2. instead of assigning data directly to an index you should assign it to product_meta first, for example, you can try this

    $item_meta['your_key] = 'your_value';
    $cart_item_data ['product_meta'] = array('meta_data' => $item_meta);