Custom cart item weight in Woocommerce












1














I am creating products that vary greatly in size and weight. I am not using WooCommerce product variants to help me with this as my products are heavily customized. I am using a third-party plugin to select from many variant options and I plan on checking these options to determine the products weight.



The issue is I want to set the product weight before the product is added to the cart. A shipping calculator on the cart will then calculate your shipping based off your cart's total weight (WooCommerce Weight Based Shipping).



I have tried 2 WooCommerce hooks pretty extensively to do this with no luck.



add_filter( 'woocommerce_add_cart_item_data', 'update_weight_on_add_to_cart', 10, 3);


and



add_action( 'woocommerce_add_to_cart', 'update_weight_on_add_to_cart', 10, 6 );


I am able to set custom fields using the add_filter. Doing this I am able to see that I successfully set the product weight to something new. BUT once I get to the cart page, the weight is reverted back to what is set on the edit product page.



This is the function I am currently using to check that:



function update_weight_on_add_to_cart( $cart_item_data, $product_id, $variation_id )
{
$product = wc_get_product( $product_id );

$weight1 = $product->get_weight();

$product->set_weight(3.45);
$weight2 = $product->get_weight();

$cart_item_data['weight1'] = $weight1;
$cart_item_data['weight2'] = $weight2;

return $cart_item_data;
}


Then I display these fields on the cart to see if I changed the data successfully using the following hook and function. (I grabbed most of this from blog posts or other StackOverflow posts)



add_filter( 'woocommerce_get_item_data', 'display_weight', 10, 2 );
function display_weight( $item_data, $cart_item ) {
$item_id = $cart_item['variation_id'];
if($item_id == 0) $item_id = $cart_item['product_id'];
$product_qty = $cart_item['quantity'];
$product = wc_get_product($item_id);
$weight3 = $product->get_weight();

$item_data = array(
'key' => __('Weight3', 'woocommerce'),
'value' => wc_clean( $weight3 ),
'display' => ''
);
$item_data = array(
'key' => __( 'Weight1', 'woocommerce' ),
'value' => wc_clean( $cart_item['weight1'] ),
'display' => ''
);
$item_data = array(
'key' => __( 'Weight2', 'woocommerce' ),
'value' => wc_clean( $cart_item['weight2'] ),
'display' => ''
);

return $item_data;
}


My most recent effort using the above code resulted in the following on the cart page.



Weight3: 1



Weight1: 1



Weight2: 3.45



Any help would be appreciated! If this can't be done this way, is there a better way to approach this issue? Maybe this needs to be done on the cart?










share|improve this question





























    1














    I am creating products that vary greatly in size and weight. I am not using WooCommerce product variants to help me with this as my products are heavily customized. I am using a third-party plugin to select from many variant options and I plan on checking these options to determine the products weight.



    The issue is I want to set the product weight before the product is added to the cart. A shipping calculator on the cart will then calculate your shipping based off your cart's total weight (WooCommerce Weight Based Shipping).



    I have tried 2 WooCommerce hooks pretty extensively to do this with no luck.



    add_filter( 'woocommerce_add_cart_item_data', 'update_weight_on_add_to_cart', 10, 3);


    and



    add_action( 'woocommerce_add_to_cart', 'update_weight_on_add_to_cart', 10, 6 );


    I am able to set custom fields using the add_filter. Doing this I am able to see that I successfully set the product weight to something new. BUT once I get to the cart page, the weight is reverted back to what is set on the edit product page.



    This is the function I am currently using to check that:



    function update_weight_on_add_to_cart( $cart_item_data, $product_id, $variation_id )
    {
    $product = wc_get_product( $product_id );

    $weight1 = $product->get_weight();

    $product->set_weight(3.45);
    $weight2 = $product->get_weight();

    $cart_item_data['weight1'] = $weight1;
    $cart_item_data['weight2'] = $weight2;

    return $cart_item_data;
    }


    Then I display these fields on the cart to see if I changed the data successfully using the following hook and function. (I grabbed most of this from blog posts or other StackOverflow posts)



    add_filter( 'woocommerce_get_item_data', 'display_weight', 10, 2 );
    function display_weight( $item_data, $cart_item ) {
    $item_id = $cart_item['variation_id'];
    if($item_id == 0) $item_id = $cart_item['product_id'];
    $product_qty = $cart_item['quantity'];
    $product = wc_get_product($item_id);
    $weight3 = $product->get_weight();

    $item_data = array(
    'key' => __('Weight3', 'woocommerce'),
    'value' => wc_clean( $weight3 ),
    'display' => ''
    );
    $item_data = array(
    'key' => __( 'Weight1', 'woocommerce' ),
    'value' => wc_clean( $cart_item['weight1'] ),
    'display' => ''
    );
    $item_data = array(
    'key' => __( 'Weight2', 'woocommerce' ),
    'value' => wc_clean( $cart_item['weight2'] ),
    'display' => ''
    );

    return $item_data;
    }


    My most recent effort using the above code resulted in the following on the cart page.



    Weight3: 1



    Weight1: 1



    Weight2: 3.45



    Any help would be appreciated! If this can't be done this way, is there a better way to approach this issue? Maybe this needs to be done on the cart?










    share|improve this question



























      1












      1








      1







      I am creating products that vary greatly in size and weight. I am not using WooCommerce product variants to help me with this as my products are heavily customized. I am using a third-party plugin to select from many variant options and I plan on checking these options to determine the products weight.



      The issue is I want to set the product weight before the product is added to the cart. A shipping calculator on the cart will then calculate your shipping based off your cart's total weight (WooCommerce Weight Based Shipping).



      I have tried 2 WooCommerce hooks pretty extensively to do this with no luck.



      add_filter( 'woocommerce_add_cart_item_data', 'update_weight_on_add_to_cart', 10, 3);


      and



      add_action( 'woocommerce_add_to_cart', 'update_weight_on_add_to_cart', 10, 6 );


      I am able to set custom fields using the add_filter. Doing this I am able to see that I successfully set the product weight to something new. BUT once I get to the cart page, the weight is reverted back to what is set on the edit product page.



      This is the function I am currently using to check that:



      function update_weight_on_add_to_cart( $cart_item_data, $product_id, $variation_id )
      {
      $product = wc_get_product( $product_id );

      $weight1 = $product->get_weight();

      $product->set_weight(3.45);
      $weight2 = $product->get_weight();

      $cart_item_data['weight1'] = $weight1;
      $cart_item_data['weight2'] = $weight2;

      return $cart_item_data;
      }


      Then I display these fields on the cart to see if I changed the data successfully using the following hook and function. (I grabbed most of this from blog posts or other StackOverflow posts)



      add_filter( 'woocommerce_get_item_data', 'display_weight', 10, 2 );
      function display_weight( $item_data, $cart_item ) {
      $item_id = $cart_item['variation_id'];
      if($item_id == 0) $item_id = $cart_item['product_id'];
      $product_qty = $cart_item['quantity'];
      $product = wc_get_product($item_id);
      $weight3 = $product->get_weight();

      $item_data = array(
      'key' => __('Weight3', 'woocommerce'),
      'value' => wc_clean( $weight3 ),
      'display' => ''
      );
      $item_data = array(
      'key' => __( 'Weight1', 'woocommerce' ),
      'value' => wc_clean( $cart_item['weight1'] ),
      'display' => ''
      );
      $item_data = array(
      'key' => __( 'Weight2', 'woocommerce' ),
      'value' => wc_clean( $cart_item['weight2'] ),
      'display' => ''
      );

      return $item_data;
      }


      My most recent effort using the above code resulted in the following on the cart page.



      Weight3: 1



      Weight1: 1



      Weight2: 3.45



      Any help would be appreciated! If this can't be done this way, is there a better way to approach this issue? Maybe this needs to be done on the cart?










      share|improve this question















      I am creating products that vary greatly in size and weight. I am not using WooCommerce product variants to help me with this as my products are heavily customized. I am using a third-party plugin to select from many variant options and I plan on checking these options to determine the products weight.



      The issue is I want to set the product weight before the product is added to the cart. A shipping calculator on the cart will then calculate your shipping based off your cart's total weight (WooCommerce Weight Based Shipping).



      I have tried 2 WooCommerce hooks pretty extensively to do this with no luck.



      add_filter( 'woocommerce_add_cart_item_data', 'update_weight_on_add_to_cart', 10, 3);


      and



      add_action( 'woocommerce_add_to_cart', 'update_weight_on_add_to_cart', 10, 6 );


      I am able to set custom fields using the add_filter. Doing this I am able to see that I successfully set the product weight to something new. BUT once I get to the cart page, the weight is reverted back to what is set on the edit product page.



      This is the function I am currently using to check that:



      function update_weight_on_add_to_cart( $cart_item_data, $product_id, $variation_id )
      {
      $product = wc_get_product( $product_id );

      $weight1 = $product->get_weight();

      $product->set_weight(3.45);
      $weight2 = $product->get_weight();

      $cart_item_data['weight1'] = $weight1;
      $cart_item_data['weight2'] = $weight2;

      return $cart_item_data;
      }


      Then I display these fields on the cart to see if I changed the data successfully using the following hook and function. (I grabbed most of this from blog posts or other StackOverflow posts)



      add_filter( 'woocommerce_get_item_data', 'display_weight', 10, 2 );
      function display_weight( $item_data, $cart_item ) {
      $item_id = $cart_item['variation_id'];
      if($item_id == 0) $item_id = $cart_item['product_id'];
      $product_qty = $cart_item['quantity'];
      $product = wc_get_product($item_id);
      $weight3 = $product->get_weight();

      $item_data = array(
      'key' => __('Weight3', 'woocommerce'),
      'value' => wc_clean( $weight3 ),
      'display' => ''
      );
      $item_data = array(
      'key' => __( 'Weight1', 'woocommerce' ),
      'value' => wc_clean( $cart_item['weight1'] ),
      'display' => ''
      );
      $item_data = array(
      'key' => __( 'Weight2', 'woocommerce' ),
      'value' => wc_clean( $cart_item['weight2'] ),
      'display' => ''
      );

      return $item_data;
      }


      My most recent effort using the above code resulted in the following on the cart page.



      Weight3: 1



      Weight1: 1



      Weight2: 3.45



      Any help would be appreciated! If this can't be done this way, is there a better way to approach this issue? Maybe this needs to be done on the cart?







      php wordpress woocommerce cart weight






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 21:40









      LoicTheAztec

      83.9k125994




      83.9k125994










      asked Nov 20 at 20:41









      SIBE Automation

      82




      82
























          1 Answer
          1






          active

          oldest

          votes


















          0














          There is some errors, mistakes and missing part… Here it's the way to do it (for all products types including product variations):



          // make and save a calculated weight as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
          function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
          // For product variations handling
          $product_id = $variation_id > 0 ? $variation_id : $product_id;

          // Get an instance of the product object
          $product = wc_get_product( $product_id );

          // The default product weight
          $cart_item_data['weight']['default'] = $product->get_weight();

          ## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
          $new_weight_value = 3.45;

          // Set the new calculated weight
          $cart_item_data['weight']['new'] = 3.45;

          return $cart_item_data;
          }

          add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
          function display_cart_item_weight( $item_data, $cart_item ) {
          if ( isset($cart_item['weight']) ) {
          // Display original weight
          if ( isset($cart_item['weight']['default']) ) {
          $item_data = array(
          'key' => __('Weight (original)', 'woocommerce'),
          'value' => wc_format_weight( $cart_item['weight']['default'] ),
          );
          }

          // Display calculated weight
          if ( isset($cart_item['weight']['new']) ) {
          $item_data = array(
          'key' => __( 'Weight (new)', 'woocommerce' ),
          'value' => wc_format_weight( $cart_item['weight']['new'] ),
          );
          }
          }
          return $item_data;
          }

          // Set the new weight in cart items
          add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
          function set_custom_cart_item_weight( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          foreach( $cart->get_cart() as $cart_item ){
          if ( isset($cart_item['weight']['new']) ) {
          $cart_item['data']->set_weight($cart_item['weight']['new']);
          }
          }
          }


          Code goes in function.php file of your active child theme (active theme). Tested and works.



          enter image description here






          share|improve this answer





















          • Thank you for all the work you've done here!!
            – SIBE Automation
            Nov 23 at 16:11










          • Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
            – SIBE Automation
            Nov 23 at 16:28










          • The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
            – LoicTheAztec
            Nov 23 at 16:33












          • Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
            – SIBE Automation
            Nov 28 at 13:44











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401178%2fcustom-cart-item-weight-in-woocommerce%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          There is some errors, mistakes and missing part… Here it's the way to do it (for all products types including product variations):



          // make and save a calculated weight as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
          function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
          // For product variations handling
          $product_id = $variation_id > 0 ? $variation_id : $product_id;

          // Get an instance of the product object
          $product = wc_get_product( $product_id );

          // The default product weight
          $cart_item_data['weight']['default'] = $product->get_weight();

          ## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
          $new_weight_value = 3.45;

          // Set the new calculated weight
          $cart_item_data['weight']['new'] = 3.45;

          return $cart_item_data;
          }

          add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
          function display_cart_item_weight( $item_data, $cart_item ) {
          if ( isset($cart_item['weight']) ) {
          // Display original weight
          if ( isset($cart_item['weight']['default']) ) {
          $item_data = array(
          'key' => __('Weight (original)', 'woocommerce'),
          'value' => wc_format_weight( $cart_item['weight']['default'] ),
          );
          }

          // Display calculated weight
          if ( isset($cart_item['weight']['new']) ) {
          $item_data = array(
          'key' => __( 'Weight (new)', 'woocommerce' ),
          'value' => wc_format_weight( $cart_item['weight']['new'] ),
          );
          }
          }
          return $item_data;
          }

          // Set the new weight in cart items
          add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
          function set_custom_cart_item_weight( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          foreach( $cart->get_cart() as $cart_item ){
          if ( isset($cart_item['weight']['new']) ) {
          $cart_item['data']->set_weight($cart_item['weight']['new']);
          }
          }
          }


          Code goes in function.php file of your active child theme (active theme). Tested and works.



          enter image description here






          share|improve this answer





















          • Thank you for all the work you've done here!!
            – SIBE Automation
            Nov 23 at 16:11










          • Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
            – SIBE Automation
            Nov 23 at 16:28










          • The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
            – LoicTheAztec
            Nov 23 at 16:33












          • Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
            – SIBE Automation
            Nov 28 at 13:44
















          0














          There is some errors, mistakes and missing part… Here it's the way to do it (for all products types including product variations):



          // make and save a calculated weight as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
          function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
          // For product variations handling
          $product_id = $variation_id > 0 ? $variation_id : $product_id;

          // Get an instance of the product object
          $product = wc_get_product( $product_id );

          // The default product weight
          $cart_item_data['weight']['default'] = $product->get_weight();

          ## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
          $new_weight_value = 3.45;

          // Set the new calculated weight
          $cart_item_data['weight']['new'] = 3.45;

          return $cart_item_data;
          }

          add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
          function display_cart_item_weight( $item_data, $cart_item ) {
          if ( isset($cart_item['weight']) ) {
          // Display original weight
          if ( isset($cart_item['weight']['default']) ) {
          $item_data = array(
          'key' => __('Weight (original)', 'woocommerce'),
          'value' => wc_format_weight( $cart_item['weight']['default'] ),
          );
          }

          // Display calculated weight
          if ( isset($cart_item['weight']['new']) ) {
          $item_data = array(
          'key' => __( 'Weight (new)', 'woocommerce' ),
          'value' => wc_format_weight( $cart_item['weight']['new'] ),
          );
          }
          }
          return $item_data;
          }

          // Set the new weight in cart items
          add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
          function set_custom_cart_item_weight( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          foreach( $cart->get_cart() as $cart_item ){
          if ( isset($cart_item['weight']['new']) ) {
          $cart_item['data']->set_weight($cart_item['weight']['new']);
          }
          }
          }


          Code goes in function.php file of your active child theme (active theme). Tested and works.



          enter image description here






          share|improve this answer





















          • Thank you for all the work you've done here!!
            – SIBE Automation
            Nov 23 at 16:11










          • Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
            – SIBE Automation
            Nov 23 at 16:28










          • The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
            – LoicTheAztec
            Nov 23 at 16:33












          • Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
            – SIBE Automation
            Nov 28 at 13:44














          0












          0








          0






          There is some errors, mistakes and missing part… Here it's the way to do it (for all products types including product variations):



          // make and save a calculated weight as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
          function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
          // For product variations handling
          $product_id = $variation_id > 0 ? $variation_id : $product_id;

          // Get an instance of the product object
          $product = wc_get_product( $product_id );

          // The default product weight
          $cart_item_data['weight']['default'] = $product->get_weight();

          ## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
          $new_weight_value = 3.45;

          // Set the new calculated weight
          $cart_item_data['weight']['new'] = 3.45;

          return $cart_item_data;
          }

          add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
          function display_cart_item_weight( $item_data, $cart_item ) {
          if ( isset($cart_item['weight']) ) {
          // Display original weight
          if ( isset($cart_item['weight']['default']) ) {
          $item_data = array(
          'key' => __('Weight (original)', 'woocommerce'),
          'value' => wc_format_weight( $cart_item['weight']['default'] ),
          );
          }

          // Display calculated weight
          if ( isset($cart_item['weight']['new']) ) {
          $item_data = array(
          'key' => __( 'Weight (new)', 'woocommerce' ),
          'value' => wc_format_weight( $cart_item['weight']['new'] ),
          );
          }
          }
          return $item_data;
          }

          // Set the new weight in cart items
          add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
          function set_custom_cart_item_weight( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          foreach( $cart->get_cart() as $cart_item ){
          if ( isset($cart_item['weight']['new']) ) {
          $cart_item['data']->set_weight($cart_item['weight']['new']);
          }
          }
          }


          Code goes in function.php file of your active child theme (active theme). Tested and works.



          enter image description here






          share|improve this answer












          There is some errors, mistakes and missing part… Here it's the way to do it (for all products types including product variations):



          // make and save a calculated weight as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
          function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
          // For product variations handling
          $product_id = $variation_id > 0 ? $variation_id : $product_id;

          // Get an instance of the product object
          $product = wc_get_product( $product_id );

          // The default product weight
          $cart_item_data['weight']['default'] = $product->get_weight();

          ## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
          $new_weight_value = 3.45;

          // Set the new calculated weight
          $cart_item_data['weight']['new'] = 3.45;

          return $cart_item_data;
          }

          add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
          function display_cart_item_weight( $item_data, $cart_item ) {
          if ( isset($cart_item['weight']) ) {
          // Display original weight
          if ( isset($cart_item['weight']['default']) ) {
          $item_data = array(
          'key' => __('Weight (original)', 'woocommerce'),
          'value' => wc_format_weight( $cart_item['weight']['default'] ),
          );
          }

          // Display calculated weight
          if ( isset($cart_item['weight']['new']) ) {
          $item_data = array(
          'key' => __( 'Weight (new)', 'woocommerce' ),
          'value' => wc_format_weight( $cart_item['weight']['new'] ),
          );
          }
          }
          return $item_data;
          }

          // Set the new weight in cart items
          add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
          function set_custom_cart_item_weight( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          foreach( $cart->get_cart() as $cart_item ){
          if ( isset($cart_item['weight']['new']) ) {
          $cart_item['data']->set_weight($cart_item['weight']['new']);
          }
          }
          }


          Code goes in function.php file of your active child theme (active theme). Tested and works.



          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 21:40









          LoicTheAztec

          83.9k125994




          83.9k125994












          • Thank you for all the work you've done here!!
            – SIBE Automation
            Nov 23 at 16:11










          • Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
            – SIBE Automation
            Nov 23 at 16:28










          • The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
            – LoicTheAztec
            Nov 23 at 16:33












          • Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
            – SIBE Automation
            Nov 28 at 13:44


















          • Thank you for all the work you've done here!!
            – SIBE Automation
            Nov 23 at 16:11










          • Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
            – SIBE Automation
            Nov 23 at 16:28










          • The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
            – LoicTheAztec
            Nov 23 at 16:33












          • Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
            – SIBE Automation
            Nov 28 at 13:44
















          Thank you for all the work you've done here!!
          – SIBE Automation
          Nov 23 at 16:11




          Thank you for all the work you've done here!!
          – SIBE Automation
          Nov 23 at 16:11












          Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
          – SIBE Automation
          Nov 23 at 16:28




          Hey again! Is there a way to change the actual weight using set_weight? Does your code do that? I want to ensure that this code meshes well with a plugin that I plan to implement called WooCommerce Weight Based Shipping. Thanks again.
          – SIBE Automation
          Nov 23 at 16:28












          The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
          – LoicTheAztec
          Nov 23 at 16:33






          The $new_weight_value = 3.45; is your calculated weight (in the first function)… It is set in the third function: $cart_item['data']->set_weight($cart_item['weight']['new']); … So In the first function you make your calculations for the weight...
          – LoicTheAztec
          Nov 23 at 16:33














          Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
          – SIBE Automation
          Nov 28 at 13:44




          Hey again, I didn't mean to leave you hanging, but I was on vacation last week and didn't get a chance to try your code until this morning. Additionally, I wanted to thank you again for your work. The code works exactly as expected and works with the plugin I mentioned as well. Thanks again, Matthew
          – SIBE Automation
          Nov 28 at 13:44


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401178%2fcustom-cart-item-weight-in-woocommerce%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'