skip to Main Content

I have a custom input field in the WooCommerce cart for every cart item. When somebody clicks update cart I want to send the extra data to the server and process that data and add it to the current cart.

I can’t find anywhere how to do this. Is this even possible?

I tried:

woocommerce_update_cart_action_cart_updated
in the $_POST variable the custom data is not available

Trough custom javascript
Run a ajax request every time the input field get’s changed. But this is interfering with the regular way to update the WooCommerce cart. Lot’s of bugs…

A hook before updating the cart
I can’t find if there’s a hook for sending extra data before updating the cart.

2

Answers


  1. Chosen as BEST ANSWER

    In the end the solution was quite simple. Since the cart is a regular HTML form you can add custom input data. When the cart is updated all the form data is serialised and sent trough with ajax. You just need to set the right name attribute on the input field.

    It took the following steps:

    1. Copy the woocommerce cart template.
    2. Add your custom input in the cart item foreach loop
    3. Give it the right name. Like this:

       name="cart[<?php echo $cart_item_key; ?>][your_custom_key]"
      
    4. Use the hook:

       woocommerce_update_cart_action_cart_updated
      
    5. In this hook you can easily access the $_POST['cart'] variable and do your stuff. For example:

      $cart = WC()->cart->cart_contents;
      
      // loop over the cart
      foreach($_POST['cart'] as $cartItemKey => $values) {
      
          $cartItem = $cart[$cartItemKey];
      
          $yourCustomValue = $values['your_custom_key'];
      
          // process the value, do something with it...
      
          $cartItem['your_custom_key'] = $yourCustomValue;
      
          WC()->cart->cart_contents[$cartItemKey] = $cartItem;
      
      }
      
    6. Et voilĂ . Now when you fill in the input field and update the cart, the data is stored in the cart. Now for example you can save the extra cart data on storing a new order or use the data to calculate a fee.


  2. You can use it like this 
    
    add_filter( 'woocommerce_update_cart_action_cart_updated', function( $cart_updated ) {
        $contents = WC()->cart->cart_contents;
        foreach ( $contents as $key => &$item ) {
            $contents[$key]['location'] = $_POST['cart'][$key]['location'];
            $contents[$key]['pickup_on'] = $_POST['cart'][$key]['pickup_on'];
            $contents[$key]['pickup_time'] = $_POST['cart'][$key]['pickup_time'];
            $contents[$key]['pickup_day'] = $_POST['cart'][$key]['pickup_day'];
            $contents[$key]['pickup_date'] = $_POST['cart'][$key]['pickup_date'];
            $contents[$key]['testing'] = 'testing done!';
        }
        WC()->cart->set_cart_contents( $contents );
        return true;
    } );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search