Skip to content

Instantly share code, notes, and snippets.

@plugin-republic
Created December 6, 2018 12:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugin-republic/525acbfc37d91e97091c6823229a1aa3 to your computer and use it in GitHub Desktop.
Save plugin-republic/525acbfc37d91e97091c6823229a1aa3 to your computer and use it in GitHub Desktop.
<?php
function prefix_update_existing_cart_item_meta() {
$cart = WC()->cart->cart_contents;
foreach( $cart as $cart_item_id=>$cart_item ) {
$cart_item['new_meta_data'] = 'Your stuff goes here';
WC()->cart->cart_contents[$cart_item_id] = $cart_item;
}
WC()->cart->set_session();
}
@ahmedzeidan
Copy link

@CUBICinfinity Thanks for the update...

Would it be possible if you can write down the full snippet and how you used it with add_action('woocommerce_add_to_cart', ?

@CUBICinfinity
Copy link

CUBICinfinity commented Mar 17, 2022

Yeah, no problem. This is still under development as I work things out. What I'm wanting to do involves manipulating the quantity and I'm storing a side value for quantity that doesn't get altered until I tell it to be altered. I cleaned this up to just what's relevant. There are other functions and line in the snippet not shown here I've been experimenting with.

function spit_cart_items() {
  foreach (WC()->cart->get_cart() as $cart_item) {
    var_dump($cart_item);
    echo "<br/><br/>";
  }
}

// https://pluginrepublic.com/how-to-update-existing-woocommerce-cart-meta-data/
function write_custom_cart_data() {
  $cart = WC()->cart->cart_contents;
  foreach( $cart as $cart_item_id=>$cart_item ) {
    if (! isset($cart_item['new_meta_data'])) {
      $cart_item['new_meta_data'] = $cart_item['quantity'];
      WC()->cart->cart_contents[$cart_item_id] = $cart_item;
    }
  }
  WC()->cart->set_session();
}

// TEST
if (in_array('administrator', wp_get_current_user()->roles)) {
  // How do we make it execute once and be a permanent meta field?
  add_action('woocommerce_add_to_cart', 'write_custom_cart_data', 4);
  add_action('woocommerce_before_cart_table', 'spit_cart_items', 11);
}

I've found that if I remove the write_custom_cart_data action from the snippet then I lose the previously saved custom data after saving the changes to the snippet. I don't know what happens if I remove WC()->cart->set_session();. I'm guessing that it won't update the cart and the WC session will act like it hasn't been modified. But I'm still discovering how WooCommerce works. I also am fairly new to the idea of sessions.

@ahmedzeidan
Copy link

Thanks @CUBICinfinity i will give this a try and update back here for feedback if any... stay awesome...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment