how do I add metadata to a cart item?

  • Open
  • avtars
    Participant
    November 15, 2019 at 4:56 am #4177
    avtars

    how do I add metadata to a cart item?

  1. Manik Malhotra
    Keymaster
    Posts: 48
    November 15, 2019 at 11:11 am #4181
    Manik Malhotra

    It turns out to be easy to do this with session data. When you’re adding an item to the cart (see the source for add_to_cart_action) you create a session variable, containing all your additional meta data:

    WC()->session->set(
    'my_session_var_name',
    array(
    'members' => $members,
    'start' => $start,
    'expiry' => $expiry,
    'etc' => $etc));

    When the user checks out, the cart data disappears, and a new order is created. You can hook into woocommerce_add_order_item_meta to add the session meta data to the order meta data:

    
    
    add_action(
    'woocommerce_add_order_item_meta', 'hook_new_order_item_meta', 10, 3);
    
    function hook_new_order_item_meta($item_id, $values, $cart_item_key) {
    $session_var = 'my_session_var_name';
    $session_data = WC()->session->get($session_var);
    if(!empty($session_data))
    wc_add_order_item_meta($item_id, $session_var, $session_data);
    else
    error_log("no session data", 0);
    }

    That’s it. You do have to figure out how to get the order metadata out and do something useful with it, though. You may also want to clear the session data, from hooks into woocommerce_before_cart_item_quantity_zero, and woocommerce_cart_emptied. There’s gist here which has some example code for this.