Woocommerce – change product price dynamically while adding to cart without using plugins

If you ever wonder how to change the product price while adding to cart.?

Now WC Fields Factory support this feature, it has advanced configuration to override the Product Pricing. You can also add custom Fee too

First, why would you ever wanted to do that.? good question. You can charge some extra fee for gift wrapping the product or let your customer buy a bakery cake without eggs or sugar for extra fee.

You will have look into the this article for how to add custom meta data in your woocommerce cart item.

Ok lets start by adding gift wrap checkbox on your product page.

Place the following code in your functions.php

function add_gift_wrap_field() {
	echo '<table class="variations" cellspacing="0">
			<tbody>
				<tr>
					<td class="label"><label>Gift Wrap It</label></td>
					<td class="value">
						<label><input type="checkbox" name="option_gift_wrap" value="YES" /> This will add 100/- extra</label>						
					</td>
				</tr>	        					
		    </tbody>
		</table>';
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );

The above code will add a check box field in your woocommerce product page, so that customer can choose whether they wanted this product as gift wrapped.

screenshot1

screen shot 1

Place the following code in your functions.php

function save_gift_wrap_fee( $cart_item_data, $product_id ) {
	
	if( isset( $_POST['option_gift_wrap'] ) && $_POST['option_gift_wrap'] === 'YES' ) {
		$cart_item_data[ "gift_wrap_fee" ] = "YES";		
	}
	return $cart_item_data;
	
}
add_filter( 'woocommerce_add_cart_item_data', 'save_gift_wrap_fee', 99, 2 );

The above code will store the ‘Gift Wrap’ option in the line item object for later use.

Place the following code in your functions.php

function calculate_gift_wrap_fee( $cart_object ) {
	if( !WC()->session->__isset( "reload_checkout" )) {
		/* Gift wrap price */
		$additionalPrice = 100;
		foreach ( WC()->cart->get_cart() as $key => $value ) {
			if( isset( $value["gift_wrap_fee"] ) ) {				
				if( method_exists( $value['data'], "set_price" ) ) {
                                        /* Woocommerce 3.0 + */
					$orgPrice = floatval( $value['data']->get_price() );
					$value['data']->set_price( $orgPrice + $additionalPrice );
				} else {
      					/* Version before 3.0 */
					$orgPrice = floatval( $value['data']->price );
					$value['data']->price = ( $orgPrice + $additionalPrice );					
				}			
			}
		}
	}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );

This is the main part, the above code will add gift wrap fee if customer has chosen to.

Place the following code in your functions.php

function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
	$meta_items = array();
	/* Woo 2.4.2 updates */
	if( !empty( $cart_data ) ) {
		$meta_items = $cart_data;
	}
	if( isset( $cart_item["gift_wrap_fee"] ) ) {
		$meta_items[] = array( "name" => "Gift Wrap", "value" => "Yes" );
	}
	return $meta_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 99, 2 );

Above piece of code will add Gift wrap option in your cart table as well as your checkout order review table.
Look at the cart total it has been changed from 8500/- ( original price ) to 8600/- ( refer screen shot 1 & 2 )

screenshot2

screen shot 2

Place the following code in your functions.php

function gift_wrap_order_meta_handler( $item_id, $values, $cart_item_key ) {
	if( isset( $values["gift_wrap_fee"] ) ) {
		wc_add_order_item_meta( $item_id, "Gift Wrap", 'Yes' );
	}
}
add_action( 'woocommerce_add_order_item_meta', 'gift_wrap_order_meta_handler', 99, 3 );

Above code will add Gift wrap option with your order item meta. Refer the screen shot 3.

screenshot3

screen shot 3

Overriding price with WC Fields Factory Plugin

WC Fields Factory is wordpress plugin which allows you to add custom fields to your woocommerce product page. If you are using WC Fields Factory to add custom fields and you wanted to override the price add the following snippet in your functions.php

From Version 2.0.0 WC Fields Factory has this option inbuilt, refer this post for further details

function calculate_cart_total( $cart_object ) {
	/* additional price that has to be added */
	$additionalPrice = 100;
	
	foreach ( WC()->cart->get_cart() as $key => $value ) {
		/* Check for the value ( or it could be any condition logic ) */
		/* Each custom field's key would be prefixed with `wccpf_` */		
		if (isset($value["wccpf_your_field_name"]) && $value["wccpf_your_field_name"] == "user entered value") {
			/* SO here the user entered a value (while adding this product to cart) for this field
			 * is matching our cretiria then change the product price  */
			if( method_exists( $value['data'], "set_price" ) ) {
				/* Woocommerce 3.0 + */
				$orgPrice = floatval( $value['data']->get_price() );
				$value['data']->set_price( $orgPrice + $additionalPrice );
			} else {
				/* Woocommerece before 3.0 */
				$orgPrice = floatval( $value['data']->price );
				$value['data']->price = ( $orgPrice + $additionalPrice );
			}
		}		
	}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );

Happy Blogging.!

Leave a Reply to Soniya Cancel reply

Your email address will not be published.

 

135 Comment(s)

  1. harvey February 2, 2018

    hello why i cannot find price rules next to Fields Meta in new version ?thanks

  2. Marco December 17, 2017

    Hi Saravana
    I would like to put a price using a snippet, but something does not fit, my web breaks,
    I hope you can help me with this, thanks in advance

    function woocommerce_calculate_color_in_front_fee( $cart_object ) {
        /* color in front price */
        $additionalPrice = 3;
        foreach ( $cart_object->cart_contents as $key => $value ) {      
            if( WC()->session->__isset( $key.’color_in_front_fee’ ) ) {
                $quantity = intval( $value[‘quantity’] );
                $orgPrice = intval( $value[‘data’]->price );
                 
                $opt = WC()->session->get( $cart_item_key.’color_in_front_fee’);
                if( $opt == “1” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 3  ) * $quantity );
                } else if( $opt == “1 color + white under base” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 6 ) * $quantity );
    } else if( $opt == “2” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 6 ) * $quantity );
    } else if( $opt == “2 + white under base” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 9 ) * $quantity );
                } else if( $opt == “3” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 9 ) * $quantity );
    } else if( $opt == “3 color + white under base” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 12 ) * $quantity );
    } else if( $opt == “4” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 12 ) * $quantity );
    } else if( $opt == “0” ) {
                    $value[‘data’]->price = ( ( $orgPrice + 0 ) * $quantity );
                }      
            }          
        }
    }
    add_action( ‘woocommerce_before_calculate_totals’, ‘woocommerce_calculate_color_in_fron_fee’, 1, 1 );

  3. Steve December 6, 2017

    In the above code for overriding price, which lines need to be edited?
    $additionalPrice = 100; // put proper price?
    “wccpf_your_field_name” for example: “wccpf_shirt_color” ?
    “user entered value” for exaple: “red”
    Will woocommerce dynamically update the price at the bottom, or only once added to cart?

    1. Saravana Kumar K December 6, 2017

      All three statements has to be updated, this will affect corresponding line item total thus affecting the grand total too.

  4. Craig November 30, 2017

    Hi Saravana,
    I wonder if you could show me how to add the extra charge after total
    so coupons can’t remove the charge.

    Thanks

  5. sjlocke November 28, 2017

    Hi,

    The code to override and add an extra charge based on a checked option from WC Fields is not working. I also tried the code listed down below from July. I add the code at the very end of my functions file, upload, and the site no longer returns anything. It used to be working fine. I have updated everything – WP, WCC, etc.

    Thanks.

    1. Saravana Kumar K November 28, 2017

      If you could wait for Fields Factory V2.0.0 (coming this week), Pricing & Fee rules for fields is built in ( Sneak Peak )

    2. Saravana Kumar K November 28, 2017

      I have also updated that Price Overriding snippet recently, please go through that one more time.

      1. sjlocke November 28, 2017

        What do I need to modify in the snippet to work with my pulldown field where the first option adds $2? Sorry – I had this figured out like a year ago.

        I’ve changed “wccpf_your_field_name” to “wccpf_add_ticket” and what do I change “user entered value” to?

        1. Saravana Kumar K November 28, 2017

          No that part is fine, the main change is overriding the price part. you have to use as it is like the below (of course change the $additionalPrice as per your logic ).

           if( method_exists( $value['data'], "set_price" ) ) {
               /* Woocommerce 3.0 + */
               $orgPrice = floatval( $value['data']->get_price() );
               $value['data']->set_price( $orgPrice + $additionalPrice );
          } else {
              /* Woocommerece before 3.0 */
               $orgPrice = floatval( $value['data']->price );
               $value['data']->price = ( $orgPrice + $additionalPrice );
          }
          
      2. sjlocke November 28, 2017

        I’ve changed the “user entered value” to “Include” which is the name of my first option value. Still doesn’t seem to do anything.

        1. sjlocke November 29, 2017

          Hey, thanks. Got it working. The page was crashing from naming the function calculate_cart_total, for some reason. I renamed it calculate_cart_tot and it works. Cheers!

          1. Saravana Kumar K November 29, 2017

            Glad you figured it out, I would really appreciate your ratings and review on WordPress Plugin site for WC Fields Factory (If you already haven’t done it)

  6. Craig November 27, 2017

    Hello Saravana,
    Enjoying your plugin WC Fields.
    Is it possible to add the extra charges as a separate line item in the cart.
    Thanks

    1. Saravana Kumar K November 27, 2017

      Hi, its coming (custom pricing and fee rules for fields) with next release (hopefully in a couple of days)

  7. Alan Foster October 22, 2017

    Hi Sir; i have added the price snippet as listed in documentation, but cart is not updating the price of which i want it to do on artwork needed option only.
    thank you
    https://athertonmedia.co.uk/product/raptor-economy-roller-banner/

  8. Glenn Rowe October 9, 2017

    I’m a little confused why the plugin wouldn’t handle the pricing itself with some of the code snippets provided.
    Currently when creating fields we enter the options like this…
    red|Red
    Why could we not enter it like this…
    red|Red|0.00
    blue|Blue|4.99
    If a third value (as shown above for the price) is omitted the system could just default the price to 0.00

    Fields types that don’t have multiple options could just have a text input to enter it in.

    If the system had the prices supplied like the above, could it not just update the total for us?
    The price for each option could be displayed beside each option.

  9. Soumya Raju August 22, 2017

    Hi, i want to add custom price based on user input, how can i do that?

  10. Kevin July 29, 2017

    So for Woo 3.1 using the WCFF Plugin here is the corrected template code

    function calculate_cart_total( $cart_object ) { 
        /* additional price that has to be added */
        $additionalPrice = 100;
         
        foreach ( $cart_object->cart_contents as $key => $value ) {                   
            /* Check for the value ( or it could be any condition logic ) */
            /* Each custom field's key would be prefixed with `wccpf_` */
            if( isset( $value[ "wccpf_your_fields_name" ] ) && ( $value[ "wccpf_your_fields_name" ] == "your value" ) ) {
                // change the price
                $orgPrice = floatval( $value['data']->get_price () );
                $value['data']->set_price ( $orgPrice + $additionalPrice );
            }               
        }
    }
    add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );
    
    1. Kevin July 29, 2017

      Now that the code working. How to do a foreach statement or bool? I.e. 6 checkbox options and each option is an added cost of say… $50. So if user picks 3 of the 6 then code will only add $150, I was thinking of changing the “your value” to “yes” and “no” instead of “red” or “blue” that way the code can be foreach “yes” add “50”…. Make sense???

  11. Walter July 28, 2017

    Hi Saravana,

    Thank you for the great plugin!
    Could you give me the word of advise though?

    I want to implement JQuery price calculator on the product page using data from the WCCPF fileds for the product so it calculates the price on the product page and adds that price to the cart upon Add To Cart button click. I am sort of beginner, so would you advise how should I address those fields and their respective data in script?

    Cheers, Walter

  12. Andy July 25, 2017

    I would be happy to pay for your time to look at this modification if it is possible.

    Thanks

  13. Andy July 25, 2017

    Hi, I have the code working for a single item now. However if the user selects more than one item, the fields are cloned as they should be. But if the first selection has the increased price then so do the rest, likewise if the first selection does not have the increased price item then neither do the rest. I hope you can help on this. Thanks

  14. Andy July 25, 2017

    Hi There,

    I am looking to have one of my fields increase the price of the product. I have seen the tutorials and code here but I am struggling.

    I have a food menu with starters and main courses on radio buttons. One of the main courses carries an extra charge. I am using the cloning function so each booking has a guest name their chosen starter and then the main course. I would like to ensure that just the selections with the field “wccpf_main_course” set to a radio button with data “Main course 4” adds a price increase. Can you advise please? This is what I am trying to implement, but nothing is happening. This code has been added to the functions.php in the theme folder:

    function calculate_cart_total( $cart_object ) {
    /* additional price that has to be added */
    $additionalPrice = 2.50;

    foreach ( $cart_object->cart_contents as $key => $value ) {
    /* Check for the value ( or it could be any condition logic ) */
    /* Each custom field’s key would be prefixed with `wccpf_` */
    if( isset( $value[ “wccpf_main_course_1” ] ) && ( $value[ “wccpf_main_course_1” ] == “Main Course 4” ) ) {
    // change the price
    $orgPrice = floatval( $value[‘data’]->price );
    $value[‘data’]->price = ( $orgPrice + $additionalPrice );
    }
    }
    }
    add_action( ‘woocommerce_before_calculate_totals’, ‘calculate_cart_total’, 99 );

  15. Kevin July 24, 2017

    Hello,
    I have variations products and using Field Factory to add product field. I have a field that is a check box with two options, but when I use the code it is not show or adding the $100 in cart. It shows the options that was selected but not the price. The code looks like it should be work but its not.
    function calculate_cart_total( $cart_object ) {
    /* additional price that has to be added */
    $additionalPrice = 100;

    foreach ( $cart_object->cart_contents as $key => $value ) {
    /* Check for the value ( or it could be any condition logic ) */
    /* Each custom field’s key would be prefixed with `wccpf_` */
    if( isset( $value[ “v3” ] ) && ( $value[ “v3” ] == “red” ) ) {
    // change the price
    $orgPrice = floatval( $value[‘data’]->price );
    $value[‘data’]->price = ( $orgPrice + $additionalPrice );
    }
    }
    }
    add_action( ‘woocommerce_before_calculate_totals’, ‘calculate_cart_total’, 99 );

    1. Kevin July 24, 2017

      function calculate_cart_total( $cart_object ) { 
          /* additional price that has to be added */
          $additionalPrice = 100;
           
          foreach ( $cart_object->cart_contents as $key => $value ) {                   
              /* Check for the value ( or it could be any condition logic ) */
              /* Each custom field's key would be prefixed with `wccpf_` */
              if( isset( $value[ "v3" ] ) && ( $value[ "v3" ] == "red" ) ) {
                  // change the price
                  $orgPrice = floatval( $value['data']->price );
                  $value['data']->price = ( $orgPrice + $additionalPrice );
              }               
          }
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );
      
      1. Kevin July 28, 2017

        Anything?

        1. Kevin July 29, 2017

          I got it!!!! lol

          function calculate_cart_total( $cart_object ) { 
              /* additional price that has to be added */
              $additionalPrice = 100;
                
              foreach ( $cart_object->cart_contents as $key => $value ) {                   
                  /* Check for the value ( or it could be any condition logic ) */
                  /* Each custom field's key would be prefixed with `wccpf_` */
                  if( isset( $value[ "v3" ] ) && ( $value[ "v3" ] == "red" ) ) {
                      // change the price
                     //FIX ONE WOO 3.1 Change  $value['data']->price ) to  $value['data']->get_price )
                      $orgPrice = floatval( $value['data']->get_price );
                     //FIX TWO WOO 3.1 Change  $value['data']->price = ( $orgPrice + $additionalPrice ); to  $value['data']->set_price( $orgPrice + $additionalPrice );
                      $value['data']->set_price( $orgPrice + $additionalPrice );
                  }               
              }
          }
          add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );
          
  16. Pingback: WooCommerce – Issue overriding product price

  17. antoine aubert June 17, 2017

    Hello there

    a million thanks for ending week(s) of misery to find THE post that finally answer all my questions. You guys are awesome.

    I am building a woocommerce for blinds for windows and it takes to dynamically calculate the price with height x width. A blind doesn’t have a constant price per square meter so I can’t use the price measurement plugin. Indeed a blind 100×400 is not the same price as 400×100 since one would have a 4x width metalic bar to roll the fabric around it and this is very costy.

    so i added 2 input field (height and width) and thanks to your article I was able to catch the hook before the cart update and I was able to query my table (with PDO) to retrieve the price from my table rather than from the simple product price.

    however when I do a add to cart, the little cart on the left side bar is showing the price from the simple product price (I put a random figure to satisfy woocommerce otherwise if the price is left blank, it says the product is not available).

    So my question is how to intercept every and any instance of woocommerce “trying to get the price”. I litterally have to be everywhere in the code and each time I have to ask my table for the price.

    my first issue is on this little cart on the left side. I need to catch that hook.

    even a greater question: how to you learn about the exact sequence that woo goes through? I mean, if I could follow the logic with a step by step debug mode, I could see which function are called when and where and then override them with a hook filter. However I got lost in the woodocs page. I found so many function with “price” in it that I can’t get out of it. I suppose wc_price() seems THE ultimate price function or again woocommerce_cart_item_price sounds amazing….well it crashed.

  18. Dan Sonic June 17, 2017

    Hi,
    I am trying to create 3 license boxes with global prices. The radio buttons don’t toggle between each selection and I cant add prices in the plugin . Can you assist me please ?

  19. Rodriguez May 31, 2017

    Hi,
    First of all, thank you for this plugin! It is great!

    I need to send custom fields data to a third party database when an order is complete.
    I don’t know what to put in the “key” field: $order->get_item_meta($item_id, ‘key’, true);

    I saw WooCommerce API JSON returns these keys (same as label):

    meta
    0
    key “NOM”
    value “RODRIGUEZ”
    label “NAME”
    1
    key “eMail”
    value “clo@imagevo.fr”
    label “eMail”
    2
    key “FIRST NAME”
    value “Clo”
    label “FIRST NAME”

    Here is the code I put in my function.php
    Is it correct?

    /* preparation of data to send to third party*/
    function send_order_to_ext( $order_id ){
    // get order object
    $order = wc_get_order( $order_id );

    // get products
    $items = $order->get_items();

    foreach( $items as $key => $item){
    $MyTab[‘1’] = $order->get_item_meta($item_id, ‘_first_name’, true);
    $MyTab[‘2’] = $order->get_item_meta($item_id, ‘_name’, true);
    $MyTab[‘3’] = $order->get_item_meta($item_id, ‘_email’, true);
    $MyTab[‘4’] = $order_id;
    }
    }
    add_action(‘woocommerce_thankyou’, ‘send_order_to_ext’);

    Thank you for your help

  20. Jack Dowson May 30, 2017

    Hello Saravana,
    I have installed the Fields Factory plugin and used 3 fields in a Product Field Group which is visible on all the products page.
    1. Check box (Add Engraving)[This should add 35 to the product price]
    2. Radio Button (To select font)
    3. Text Field (To insert text to be engraved)

    I just want support(code snippet) to add 35 extra to price on the product page itself if checkbox is checked.
    Help me out with this.

    Thanks in Advance.

  21. pranay May 24, 2017

    i am using wc field factory plugin it makes the text field on product page but their value is not showing on cart and checkout page.

  22. deko May 16, 2017

    I already put the codes in the functions.php but do not add the extra amount, everything else if it works correctly. I have the wordpress version 4.7.4 and woocommerce version 3.0.6

    1. Saravana Kumar K May 24, 2017

      Updated for WC 3.0+

      1. E222W June 9, 2017

        Hello
        A really great plugin, thank you for it!
        I have a question about this:
        When I put an item in the basket and put it
        Articles then again calls are all inputs empty.
        Are the data not stored in a session?
        Is there a solution for this?
        I work with the latest WordPress / Woocommerce version.

        Thanks for a feedback

  23. Valentin April 18, 2017

    Hello, Saravana! Thank you for your efforts and your great plugin!
    I experienced difficulties with WooCommerce 3.0 as the code wasn’t working properly, but rolling back to 2.6.14 did the job well.
    I have a question tho – as the prices are not changed dynamically with ajax on selecting a certain addon, the mini cart prices are also not changing and showing the original prices instead of the price + addons. Have you thought about a workaround about the mini cart prices?
    Thanks very much once again!

  24. Joyce April 12, 2017

    Hi, Thanks for this plugin. I am trying to follow the code in ‘Overriding price with WC Fields Factory Plugin’ above and everything is working if “Fields Cloning” is off, however, I am not able to make it to work if it is on, any help would be appreciated, thanks a lot.

  25. Graham Cooper April 12, 2017

    Hi Saravana,

    Great post! Slight question, how can I pass a price thats generated by a custom function to the calculate_gift_wrap_fee function? Would I have to save that into a session variable or could I call the calculate_gift_wrap_fee function instead of having to use the hook woocommerce_before_calculate_totals? I basically want a function that can add to cart, and change the price similar to your example. (I’m removing the add to cart button).

  26. john April 5, 2017

    Can any one help me that i want remove cart item with ajax actually i included cart page on product archive page woocommerce where ajax not working please help.

  27. Mueed K March 6, 2017

    Hi,

    A life easer plugin. I am creating a rental system where people will have to choose “pickup date/time” and “drop-off date/time”, I those date/time fields as admin and showed them on product, cart pages as well. I want to achieve the following by the date fields;

    1- Update price dynamically based on the date/time selection, compare it with general wc price (that would be considered as hourly price) and update the price based on the date/time selection by the user.
    2- Disable selected/reserved dates, i.e. if the product inventory is set to be 1 and one user rent the product for any date so it should be disable for booking/renting until the drop-off date is met.
    3- Show only those dates for the user to pick which added by the admin while adding the product. i.e if admin has set 3rd march to 15th march, the user should be able to select the dates between 3rd march to 15th march only.

    Looking forward to hear back from you. 🙂

    1. Saravana Kumar K March 15, 2017

      Hi, as this is a vary narrow requirement, we cannot abstract it to make as a functionality for plugin. but this is doable by following the snippet given in the post. please drop us a mail that what are the method you have tried, and we will try to help you from there.

  28. Mueedullah March 5, 2017

    Hi,

    A life easer plugin. I am creating a rental system where people will have to choose “pickup date/time” and “drop-off date/time”, I those date/time fields as admin and showed them on product, cart pages as well. I want to achieve the following by the date fields;

    1- Update price dynamically based on the date/time selection, compare it with general wc price (that would be considered as hourly price) and update the price based on the date/time selection by the user.
    2- Disable selected/reserved dates, i.e. if the product inventory is set to be 1 and one user rent the product for any date so it should be disable for booking/renting until the drop-off date is met.
    3- Show only those dates for the user to pick which added by the admin while adding the product. i.e if admin has set 3rd march to 15th march, the user should be able to select the dates between 3rd march to 15th march only.

    Looking forward to hear back from you. 🙂

  29. jordan March 4, 2017

    Is there a plugin i can install that will allow me to change the prices based from what the customer selects? This would be extremely helpful for me

    1. Saravana Kumar K March 5, 2017

      Hi, No plugins yet, but we are building premium version of WC Fields Factory which has that option.

      1. Mueed K March 11, 2017

        I have posted about a week ago but still didn’t get it approved and answered.

    2. Glenn Rowe October 9, 2017

      With a slight mod of the plugin could this work…

      Currently when creating fields we enter the options like this…
      red|Red
      Why could we not enter it like this…
      red|Red|0.00
      blue|Blue|4.99
      If a third value (as shown above for the price) is omitted the system could just default the price to 0.00

      Fields types that don’t have multiple options could just have a text input to enter it in.

      If the system had the prices supplied like the above, could it not just update the total for us?
      The price for each option could be displayed beside each option.

  30. Edison Rodriguez Dominguez December 29, 2016

    Hi Saravana, your articles just save my life bro, thank you very much for this job, my question is:

    how to use a $var that comes from external text retrieved using $e->innertext

    what im trying to achieve is $additionalPrice = $e->innertext; but doesnt work, im using file_get_html somewhere else to retrieve the value of $e->innertext but i would like to use this value also like $additionalPrice = $e->innertext

    i hope you understand what im trying to do, if you need to see what im doing please contact me, this is really important to me.

  31. Pingback: woocommerce – custom input field | Walter's blog

  32. WooNeophite October 13, 2016

    Hi Sarvana, Thanks for the wonderful plugin. I have included a custom field (number) using your plugin to product page to which i allocated a default number. I would like to show this custom field in the header section of the theme which is directly related to Update cart event. So if a certain product is added to cart this custom field gets updated similar to cart based on default value defined in WC Product Field Group. Basically it’s like a commission per product a user makes when adding to cart. Similarly when removing the item from cart this custom field subtracts the commission. Any pointers would be appreciated. Thanks

  33. Adam October 3, 2016

    Thank you for the reply.

    The problem still persists. I’ve managed to get around it by simply dividing the amount by 2. Its a hack but works for now. But the weirdest thing is that after the make payment function – the amount (divided by two) is added once again which is a bit of a problem this time.

    Any ideas on a workaround?

  34. vinay October 2, 2016

    Hi Sarvana, Thanks for this informative article, however my problem is bit different I am doing some custom calculation in my product page and then using WC Factory field plugin input field to store that total in product page which will be my final total in cart page, so I want to know how can i send that total to my final cart page. As in your article you are adding manual amount as ” $additionalPrice = 100;” but i want to get that from my product page total field.

    1. Saravana Kumar K October 3, 2016

      That was easy, see the updated snippet

      function calculate_cart_total( $cart_object ) { 
          foreach ( $cart_object->cart_contents as $key => $value ) {                   
              /* Check for the value ( or it could be any condition logic ) */
              /* Each custom field's key would be prefixed with `wccpf_` */
              if( isset( $value[ "wccpf_your_fields_name" ] ) && ( $value[ "wccpf_your_fields_name" ] == "your value" ) ) {
                  // change the price
                  $orgPrice = floatval( $value['data']->price );
                  $value['data']->price = ( $orgPrice + $value[ "wccpf_your_total_field_name" ] );
              }               
          }
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );
      
  35. Adam September 30, 2016

    Hello. And thanks for the script.
    I’m trying to achieve a calculation based on user input – the user can specify additional drivers and co drivers quantity each should multiply the additional person price and add it to the total of the product

    function calculate_aditional_fees( $cart_object ) {
      if( !WC()->session->__isset( "reload_checkout" ) ) {
    
        $additional_price = get_option( 'additional_person_price' );
        $additional_driver_price = get_option( 'additional_driver_price' );
    
        foreach ( $cart_object->cart_contents as $key => $value ) {
          if ( $additional_driver_price > 0 || $additional_price > 0 ) {
            $additional_price *= $value['additional-persons'];
            $additional_driver_price *= $value['additional-drivers'];
            $cart_object->cart_contents[$key]['data']->price = floatval( $value['data']->price ) + $additional_driver_price + $additional_price;
          }
        }
      }
    }
    

    any Idea how to fix this (I’ve tried many things but it still calculates it wrong).

    1. Saravana Kumar K October 3, 2016

      You may try the below snippet

      function calculate_aditional_fees( $cart_object ) {
      	if( !WC()->session->__isset( "reload_checkout" ) ) {
      		foreach ( $cart_object->cart_contents as $key => $value ) {
      			if ( $additional_driver_price > 0 || $additional_price > 0 ) {
      				
      				$additional_price = get_option( 'additional_person_price' );
      				$additional_driver_price = get_option( 'additional_driver_price' );
      				
      				$additional_price = floatval( $additional_price ) * intval( $value['additional-persons'] );			
      				$additional_driver_price = floatval( $additional_driver_price ) * intval( $value['additional-drivers'] );
      				
      				$cart_object->cart_contents[$key]['data']->price = floatval( $value['data']->price ) + $additional_driver_price + $additional_price;
      				
      			}
      		}
      	}
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_aditional_fees', 99 );
      
  36. Sebastian September 28, 2016

    Hi,
    thanks for great plugin and this tutorial!
    the only option that I miss is easy adding price when someone check checkbox, radio button or select option.
    You can implement adding price option to in plugin field “options, Enter each options on a new line like this eg. red|Red”?
    if you use options red|Red|20 , price will go up by 20 if someone check this option.
    same if multiple options are checked original price+20+10 etc.

    REGARDS!
    Sebastian

    1. Saravana Kumar K October 3, 2016

      Hi,

      thanks, I am working on premium version, which will include that option as well, but any way you can do it yourself also, please refer the following article for that.

  37. jochen September 27, 2016

    Hej,
    how is this actually working with a variation product?

    I tried your code above, but it is not working. However, if I do a var_dump($value) there is no “price” given. Can you help me? 😉

    Thanks!

  38. Mohit Kathpal August 16, 2016

    Hi Saravana
    Thanks for this great article. However, my requirement is little different. Using your other beautiful article ‘Adding custom fields to product’ , I have managed to add custom fields into single product this way. On submitting a form, it will redirect me to a single product page where all the custom fields will be pre-populated with form POST data. In this form I also have custom price. Now I want to replace the price of the product with this custom price. Is it possible by any means? Please help.

    Thanks in advance.

    1. Saravana Kumar K August 25, 2016

      Sorry for the late reply, Yes you can do that. and it’s very simple too.

      function calculate_gift_wrap_fee( $cart_object ) {  
          if( !WC()->session->__isset( "reload_checkout" )) {
              /* Gift wrap price */
              $additionalPrice = 100;
              foreach ( $cart_object->cart_contents as $key => $value ) {
                  if( isset( $value["product_id"] == your_product_id ) ) {
                      $value['data']->price = ( $_POST['your_custom_pricing_field'] );
                  }
              }   
          }   
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );
      
  39. mitchel August 2, 2016

    is it possible to add those gift wrap fieldes only for specific products? now its displayed for all my products

    1. Saravana Kumar K August 6, 2016

      Yes you can

      function add_gift_wrap_field() {
          global $post;
          if( $post->ID == "your product id" ) {
          echo '<table class="variations" cellspacing="0">
                  <tbody>
                      <tr>
                          <td class="label"><label>Gift Wrap It</label></td>
                          <td class="value">
                              <label><input type="checkbox" name="option_gift_wrap" value="YES" /> This will add 100/- extra</label>                        
                          </td>
                      </tr>                             
                  </tbody>
              </table>';
          }
      }
      add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
      
  40. Rajesh July 21, 2016

    calculate_gift_wrap_fee() function execute twice, as it add the price 2 times. what to do?

    thanks in advance

  41. Dennis July 13, 2016

    Hi Saravan,

    Great code! It helped me out a lot.
    The only issue I have now is that the Totalprice is updated with 100, but the Price is still the price without fee.
    How can I have them both updated with the fee?

    Regards,
    Dennis

  42. Chris Jakubowski July 6, 2016

    hi, how do I put the plugin code into the catalogue grid display of my products – just about the “price” and “add to cart” button

  43. Chris Jakubowski July 6, 2016

    Hi, if I wanted the custom field to show on the product category catalogue page,how would I go about doing this?

  44. Mohamed June 7, 2016

    Hello Saravan
    i hope to help me i need add tax field below price field in product page i used this code
    add_filter( ‘woocommerce_get_price_html’, ‘test’, 10, 2 );

    function test( $price_html, $_product ) {
    echo $price_html
    . ” . ‘Tax 7%: ‘ . str_replace( ‘amount’, ‘tax-amount’, wc_price( $_product->get_price() * 0.07 ) );
    }

    add_action( ‘woocommerce_before_customer_login_form’, ‘jk_login_message’ );
    function jk_login_message() {
    if ( get_option( ‘woocommerce_enable_myaccount_registration’ ) == ‘yes’ ) {
    ?>

    <?php
    }
    }
    working well but the problem when the client or customer change attribute the total price is changed but the tax field is not change
    can you help me to add action to change the tax filed to dynamic price

  45. Soumyadip Guha May 20, 2016

    Hello Saravan,

    I have faced same issue like price is added twice after proced payment while customer create his account during checkout. Can you please look into this issue. It will be very helpful for us.

    1. Saravana Kumar K May 23, 2016

      Hi I have update the calculate_gift_wrap_fee() function, which will fix the issue. I have also answered in StackOverflow, someone asked the same question.

  46. axelr May 18, 2016

    Hi Saravan, I updated your code in my function.php page but I’have still the problem. The gift price is added twice in the total price…sorry ! if you add a product in cart and selected the gift, the total price is correct in the checkout, but if the customer create his account in same process than his checkout then the price is added twice after proced payment. You can try on my store (this a beta store the paiement is not active yet), here the link: http://scanetmoi.com/LEF/boutique/trottinettes-electriques/trot1/
    hope that helps.
    Regards,
    Axel

    1. Saravana Kumar K May 23, 2016

      Hi I have update the calculate_gift_wrap_fee() function, which will fix the issue. I have also answered in StackOverflow, someone asked the same question.

  47. Craig Brown May 17, 2016

    I considered this plugin ” for the name alone” but when I drilled deeper I saw most of the “features” are scripts you need to insert into your functions.php file. Why do I need a plugin at all if I have to insert code? That’s why I wanted a plugin, so I didn’t have to insert code, so I didn’t have to make & maintain a child theme.

    1. Saravana Kumar K May 17, 2016

      Hi Craig, this article is not about any plugin, it’s about changing cart item price dynamically without using any plugins. by the way which plugin you mean.? WC Fields Factory.?

  48. axelr May 16, 2016

    I reply to myself for more information. If the customer is already logged then everythings works fine. The gift price is added twice only when a customer added product in cart and proceed to checkout and when he is creating his account during process. If you have an idea becouse honestly I don’t understand why this issue. Thanks for your quick answer. regards, AxelR

    1. Saravana Kumar K May 17, 2016

      Hi axelr,

      I have updated my article itself ( which I was planning for very long time ), now no $_SESSION required. I have used $cart_item_data instead. this one is used for carrying additional data for each cart line items. So please go through the article again ( especially the code parts ), you will get a clear idea, and I am pretty sure you won’t face any issue anymore.

  49. axelr May 16, 2016

    Hi Saravana, I seen that, when the user has added his product in the cart and when he is not already registered to the store, the Gift price is added twice. example, add a product in the cart, and goes to procede to the order, then fill your name, adress….and pay, then I can see that the price gift is added agian… Did you alerady seen that? Thanks for your answers.

  50. roshan Karunarathna May 13, 2016

    hi there i have a field created as package weight i need to get that field value in to my shipping cost calculator as this

    foreach ( $package['contents'] as $item_id =&gt; $values ) {
    	  $_product  = $values['data'];
    	  $weight =	$weight +wc_get_order_item_meta( $item_id, "package_weight", true );
              $dimensions = $dimensions + (($_product-&gt;length * $values['quantity']) * $_product-&gt;width * $_product-&gt;height);
    }
    

    but it gives me nothing can you help me to figure this out.Thanks!

    1. Saravana Kumar K May 13, 2016

      Hi try this,

      foreach ( $package['contents'] as $item_id => $values ) {
      	$_product  = $values['data'];
      	$weight =	$weight + $values[ "package_weight" ];
      	$dimensions = $dimensions + (($_product->length * $values['quantity']) * $_product->width * $_product->height);
      } 
      

      I guess you used WC Fields Factory to add custom fields, in that case the above snippet will work.

  51. axelr May 8, 2016

    Hello, many thanks for sharing your code. It works fine for me after made a small correction.
    There is a calculation error in the cart with the code.
    So you have to replace the code:

    $value['data']->price = ( ( $orgPrice + $additionalPrice ) * $quantity );
    

    by

    $value['data']->price = ( $orgPrice + $additionalPrice ) ;
    

    Otherwise the quantity is multiply in price AND in the total price.
    So many thanks again.

    Regards,
    AxelR

    1. Saravana Kumar K May 13, 2016

      Hi thanks for pointing out, it’s been updated.

  52. Gio April 27, 2016

    I’m having an issue where if I offer a subscription product that gets charged on either a monthly or yearly subscription with a savings on prepaying for the year, that is the price that shows for the product up top.

    Example:

    Product: From $499.88 / year

    monthly 49.99
    yearly 499.88 – $100 savings

    I just want it to show the monthly price up top. How can I achieve this? Is this what you’re going to offer with your plugin?

  53. brijesh April 17, 2016

    Hi Sarvana

    Thanks for sharing awesome code. But i want to know is it possible after rendering custom fields with Cart data, could user edit his/her cart for custom fields. It seems there is no way to do this. If it possible it would be great.

    1. Saravana Kumar K April 25, 2016

      This is the feature which I am still working on, probably available with my feature releases ( I mean WC Fields Factory ).

  54. KingSlayer21 April 8, 2016

    Hi! Instead of checkbox, can I use select input instead? How can I save the value of it? Thanks

    1. Saravana Kumar K April 25, 2016

      Yes you can, same code will work, except you will have to change the checkbox field into select field in the add_gift_wrap_field

  55. Kotresh April 1, 2016

    Hi Saravana,
    Its an awesome plugin , thanks a lot for publishing it for free 🙂 . I could add custom text field on to product page , I have a requirement where in as soon as user enters value in the custom text filed the order price should get multiplied by the number in custom field dynamically , how can I achieve this .

  56. Soumyadip March 4, 2016

    Hello,

    How i will add “Gift wrap:Yes” text in checkout page under product name.

    Thanks

    1. Saravana Kumar K March 8, 2016

      Hi use this filter to woocommerce_checkout_cart_item_quantity to add your custom text under product name in checkout review order table. for more info refer /wp-content/themes/your-theme/woocommerce/checkout/review-order.php template.

  57. Soumyadip March 4, 2016

    Hello,

    How i will add “Gift wrap:Yes” in checkout page under product name.

    Thanks

  58. RadGH February 20, 2016

    Excellent set of articles sir!

    Could you write an addition to customize the appearance of order meta on the backend (when viewing an order as an admin)? Current, simple data is stored as plain key/value but arrays do not appear, and I personally do not like to show the raw meta key (“_vv_adjusted_price” should be “Adjusted Price”).

    It tried using the hook “woocommerce_order_meta_end”, but this appears to only be useful for email and for the customer’s view of the order screen (on the front end).

    1. Saravana Kumar K February 20, 2016

      Hi, that’s simple, Change your key.

      wc_add_order_item_meta( $item_id, "Adjusted Price", $price ); 
      
  59. Soumyadip February 19, 2016

    Hello,

    calculation error and i think it is because woocommerce woocart pro plugin. So can you please inform me is there any issue with this plugin

    1. Saravana Kumar K February 19, 2016

      Hi,

      Could be, may be you can increase the priority values for woocommerce_before_calculate_totals action hook, so that it will be called at a last one ( after all other handlers are executed ).

      So increase the priority value like this

      add_action( 'woocommerce_before_calculate_totals', 'calculate_cart_total', 99 );
      
  60. Soumyadip Guha February 18, 2016

    Hello Saravana,

    I am using your above code, it is working fine in cart page but in checkout page it is not working. can you please inform me why it is happening.

    1. Saravana Kumar K February 18, 2016

      Hi, not working means, calculation error.? ( or ) it’s not displaying correctly in check page alone.?

  61. Shawn February 16, 2016

    Good day Saravana,
    I put your code in to work and it works wonderful. I adjusted the price update formula as below:

    $bagsizeselected = WC()->session->get($key.'_bag_size_fee');
    if($bagsizeselected == "tenlb") {
          $value['data']->price = ( ( $orgPrice * 10 ) );
    }
    

    But there is one issue. Like say the the unit price is now 89.90. But if I go to cart page, the unit price shows as 899.00. However the sub-total is fine which is 89.90. Looks like the function gets triggered twice ?
    Do you mind to explain please how can I avoid this from happening?

    Please see here the screen shot: http://imgur.com/aKZojtC

    1. Saravana Kumar K February 16, 2016

      Hi shawn,

      I guess you should be ADDING not MULTIPLYING

      $value[‘data’]->price = ( ( $orgPrice + 10 ) );
      
  62. Aung February 6, 2016

    Hi ,
    Thanks for your great plugin , but I am totally new here .
    I can collect all the custom data but
    How can custom input price be added to the cart and add a fix fee to the cart before Check out ?
    Many Thanks !

    1. Saravana Kumar K February 9, 2016

      Hi you could use `woocommerce_before_calculate_totals` hook for this purpose, you might find this article useful.

  63. Maciej January 17, 2016

    Hello, for me everything works like a charm. But how pass this data to order so I can see it in admin order details? For example I ordered 2 same products, one is a gift and second is not and I want to know which one is gift? In admin panel in orders I see only that 2 products were ordered.

    1. Saravana Kumar K January 21, 2016

      Hi, you could use woocommerce_add_order_item_meta hook for this purpose. for example do some thing like this.

      function my_custom_order_meta_handler( $item_id, $values, $cart_item_key ) {
      	if( WC()->session->__isset( $cart_item_key.'_gift_wrap_fee' ) ) {
      		wc_add_order_item_meta( $item_id, "gift_wrap", 'Yes' );
      	}	
      }
      add_action( 'woocommerce_add_order_item_meta', 'my_custom_order_meta_handler', 1, 3 );
      
  64. Deniz January 10, 2016

    Thank you so much for the article. It works fine.
    Just one answer I need. I need to use this for only 3 items. How can I filter products? Which function do I need to change?

    Thanks in advance!

    1. Saravana Kumar K January 13, 2016

      Hi, that could be done, for example if you wanted to updated price only for products that belongs to certain category, do some thing like this below.

      function calculate_gift_wrap_fee( $cart_object ) {
          /* Gift wrap price */
          $additionalPrice = 100;
          foreach ( $cart_object->cart_contents as $key => $value ) {       
              if( has_term( "your_term", "product_cat", $value['product_id'] ) ) {
                // do your calculations
              }               
          }
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 1, 1 );
      
  65. Sean Herbert December 10, 2015

    The code for applying cost to the cart based on a WC Fields Factory field needs adjustment. The “$orgPrice = intval…” line should be floatval. Using intval will throw away $0.50 on a $9.50 product.

    1. Saravana Kumar K December 10, 2015

      Hi, thanks, updated.!

  66. Piotr December 8, 2015

    I use WC Fields Factory Plugin with bookable product, when I add to card product have error “Notice: Undefined index: wccpf_polee in plugins/wc-fields-factory/classes/product-form.php on line 252”. Is it possible integrate?

  67. Sean November 30, 2015

    Hi – trying to get the WC Fields Factory version working (have latest versions of plugin, WooCommerce and WordPress installed) but the basket price is not updating. I am using the following code in my functions.php file:

    function calculate_cart_total( $cart_object ) {

    /* additional price that has to be added */
    $additionalPrice = 5.50;

    foreach ( $cart_object->cart_contents as $key => $value ) {
    /* This will bring all the custom field objects that belongs to this product */
    $all_fields = apply_filters( ‘wccpf/load/all_fields’, $product_id );
    /* Iterate through all the field groups */
    foreach ( $all_fields as $fields ) {
    /* Iterate through all the fields */
    foreach ( $fields as $field ) {
    /* Check for your intended custom fields */
    if( $field[“name”] == “New_Logo_Upload” ) {
    $fvalue = WC()->session->get( $value[‘wccpf_unique_key’].$field[“name”] );
    /* Check for the value ( or it could be any condition logic ) */
    if( $fvalue == “yes” ) {
    //change the price
    $quantity = intval( $value[‘quantity’] );
    $orgPrice = intval( $value[‘data’]->price );
    $value[‘data’]->price = ( ( $orgPrice + $additionalPrice ) * $quantity );
    }
    }
    }
    }
    }
    }
    add_action( ‘woocommerce_before_calculate_totals’, ‘calculate_cart_total’, 1 );

    I have changed the $additionalPrice value and if( $field[“name”] == “your field” ) to if( $field[“name”] == “new_logo_upload” ) as seen in the Edit WC Product Field Group page in WP.

    This field is a radio button with yes and no choices.

    But when I select yes and add the product to the cart, the additional price is not added.

    Can you see if I have missed something!

    Thank you

    1. Vizal January 12, 2017

      Hello, I have added the above function to change price in cart, before it was working perfectly when I have used “$all_fields = apply_filters( ‘wcff/load/all_fields’, $product->id, ‘wccpf’ ); ” , even on server which I am going to give you link also working good, but at local it is not working now. It’s not printing print_r($all_fields.XXX);, its shows only “ArrayXXX” like this only and its is now going inside to print “print_r($fields);”, so its stop after from this.Even apply_filters( ‘wccpf/load/all_fields’, $product_id ); this also not working for me, so I am not getting all values, I have tried each and everything. Please help me out in this matter. I have added 2 more radio buttons on local. so its working not working on local, on server shows changing value…

  68. Pingback: Saravana Kumar K on "[Plugin: WC Fields Factory] Change Price?" * Best Wordpress Themes - Reviews

  69. Pingback: Add custom fields to woocommerce product page

  70. Matheo November 18, 2015

    Hi,everything works well but page checkout(page with select payment) , forms with cart and select payment is disabled.

  71. shivali November 5, 2015

    I like the code. but I want custom multiple check box and these check box show the product page, and also add to cart

  72. Matheo October 30, 2015

    if( $field[“name”] == “your field” ) is ok , return my field name
    but
    $fvalue = WC()->session->get( $key.$field[“name”] );

    not working, the variable is always empty….

    1. Saravana Kumar K October 30, 2015

      Hi,

      Try this instead, $fvalue = WC()->session->get( $value['wccpf_unique_key'].$field["name"] )

      Latest version of WC Fields Factory has been slightly modified, I will update the article.

  73. Marcus Torres October 24, 2015

    Good afternoon! good tutorial!
    I wonder if it would be possible to edit in the cart page by checking or unchecking the checkbox, and thus changing the price as on the product page? if so how would you do? and also possible to control this field putting increased specific values for each product in the wordpress admin? thank you

  74. sonu shokeen September 10, 2015

    i want to specific user can purchase any five product free every month. i work hard but still unable..
    i hope you can help me , thanks in advance

    1. Saravana Kumar K September 10, 2015

      Hi, you can achieve this by using User Meta combined with the code provided in this post.

  75. Soniya July 30, 2015

    HI Saravana,
    I tried the above code . i don’t want any gift packing type checkbox, but want to add some extra fee.
    And i was able to do that and changed price was coming on cart page. but when i go to checkout page for some time it display the same price but after some time waiting spinning comes and it change the price.
    and display the original price ( no updated price). i am stuck here. tired some more method but no success.
    Please help me it’s really urgent.Thanks in advance.

    1. Saravana Kumar K July 31, 2015

      Not sure what that issue would be, might a side effect from one of the plugin or misusing of hook might caused this. If you still has this issue send me your functions.php alone, so that I can check.

  76. D Mun July 21, 2015

    Nice piece of code. Question:

    What would I do if I want the product to be inserted twice. So I want a product WITH the gift wrap, and a product WITHOUT the gift wrap. But at the moment is just updates the cart (so instead of 2 single products, I get 1 product with an amount of 2).

    1. Saravana Kumar K July 21, 2015

      Don,

      function force_individual_cart_items($cart_item_data, $product_id)
      {
          $unique_cart_item_key = md5( microtime().rand() );
          $cart_item_data['unique_key'] = $unique_cart_item_key; 
          return $cart_item_data;
      }
      add_filter( 'woocommerce_add_cart_item_data','force_individual_cart_items', 10, 2 );
      
      1. D Mun July 21, 2015

        Awesome! It works. Only thing that might be a bug, don’t know.

        Say the normal price is 30. With gift wrap selected it becomes 130. If I add 2 product to the cart, the total amount get multiplied twice. I has to become 260, but it’s 520 now. Looks like the multiplier is fires twice.

      2. D Mun July 21, 2015

        You can ignore my last comment. Although it is a bug, I don’t need the quantity anymore =p

        BUT, one last thing that I don’t get. My product is 30. The gift wrap is 100. When selected and added to the cart, it indeed says 130. But when I continue to checkout, the form updates the total to 230, why’s that? I can pass a link if you want.

  77. Sam J April 10, 2015

    Hi Saravana!
    Really an amazing tutorial!!

    Would like to ask you, if is there any way to change the title of the product too? For example, Fossil Grant Wrapped etc.?

    I’m using your fantastic customization in a foundry website that uses user-generated contents to calculate final price (people upload a 3d file, a php script calculates its volume, the price gets calculated with $basic_price * $volume );

    It would be extremely useful to have the Name/Title of the product and order to change too, based on the name of the file.

    Would it be possible using the same strategy you used? Does it need different hooks?

    Thank you and have a great day!

  78. vimal March 26, 2015

    Hi Saravanakumar,

    I tried to use the below function, but its not working for me. The “woocommerce_before_add_to_cart_button'” hook is not working. I am using WordPress 4.1 and Woocommerce 2.3.5 What would be the reason? Please suggest me.

    The same code you have mentioned above..
    function add_gift_wrap_field() {
    echo ‘

    Gift Wrap It

    This will add 100/- extra

    ‘;
    }
    add_action( ‘woocommerce_before_add_to_cart_button’, ‘add_gift_wrap_field’ );

    Thanks & Regards
    P.vimal raj Kumar

    1. Saravana Kumar K March 26, 2015

      Hi Vimal, Your WP & Woo versions are supported, what theme you are using.? does your theme supports woocommerce_before_add_to_cart_button hook.?

  79. m schmitz March 23, 2015

    Hi this is great, but i was wondering: this must also be possible with an selectfield (dropdown)

    Could you give an example of using a select dropdown of the above code.

    By example when you have a select dropdown

    option one price is 100
    option two price is 120
    option tree is 140

    Could you give an example of how the price calculation works then and the validation?

    Kind regards

    1. Saravana Kumar K March 23, 2015

      Hi,

      That can be achieved through woocommerce variable product.

      If you still wanted to do it manually do some thing like this.

      function add_gift_wrap_field() {
      	echo '<table class="variations" cellspacing="0">
      			<tbody>
      				<tr>
      					<td class="label"><label>Choose the options</label></td>
      					<td class="value">
      						<select name="option_gift_wrap">
      							<option value="one">One</option>
      							<option value="two">Two</option>
      							<option value="three">Three</option>
      						</select>						
      					</td>
      				</tr>	        					
      		    </tbody>
      		</table>';
      }
      add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
      

      and in woocommerce_before_calculate_totals section.

      function calculate_gift_wrap_fee( $cart_object ) {
      	/* Gift wrap price */
      	$additionalPrice = 100;
      	foreach ( $cart_object->cart_contents as $key => $value ) {		
      		if( WC()->session->__isset( $key.'_gift_wrap_fee' ) ) {
      			$quantity = intval( $value['quantity'] );
      			$orgPrice = intval( $value['data']->price );
      			
      			$opt = WC()->session->get( $cart_item_key.'_gift_wrap_fee');
      			if( $opt == "one" ) {
      				$value['data']->price = ( ( $orgPrice + 100  ) * $quantity );
      			} else if( $opt == "two" ) {
      				$value['data']->price = ( ( $orgPrice + 120 ) * $quantity );
      			} else if( $opt == "three" ) {
      				$value['data']->price = ( ( $orgPrice + 140 ) * $quantity );
      			}		
      		}			
      	}
      }
      add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 1, 1 );
      
      1. m schmitz March 24, 2015

        Hi yes i know, this can be handeled by variable product. but I always have the same variations and then its a lot of work when i constantly have to use the default woocommerce variable product. Cauld you tell me also how this peace of code changes:

        function save_gift_wrap_fee( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null ) {
        	if( $_POST['option_gift_wrap'] === 'YES' ) {
        		WC()->session->set( $cart_item_key.'_gift_wrap_fee', 'YES' );
        	} else {
        		WC()->session->__unset( $cart_item_key.'_gift_wrap_fee' );
        	}	
        }
        add_action( 'woocommerce_add_to_cart', 'save_gift_wrap_fee', 1, 5 );     
        

        Or should it already work? Cause the form indead shows up in productpage, but when i go to my cartpage there isn’t changed anything to the price

        kind regards

        1. Saravana Kumar K March 24, 2015

          It should be like.

          function save_gift_wrap_fee( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null ) {
          	if( isset( $_POST['option_gift_wrap'] ) ) {
          		WC()->session->set( $cart_item_key.'_gift_wrap_fee', $_POST['option_gift_wrap'] );
          	}
          }
          add_action( 'woocommerce_add_to_cart', 'save_gift_wrap_fee', 1, 5 );
          
          1. SJ October 29, 2015

            Hello,
            I tried to use dropdown using your code, but it didn’t work.
            Could it be because of woocommerce updates? Or what is it?
            Thanks

  80. Gabrielle January 15, 2015

    Hi, i try your method already, but i have problem with price validation.
    Everything is ok when i check only 1 of 2 checkbox inputs,
    the price from input will add to my product price, but when i check both inputs
    the price will = product_price+price from second checkbox only
    If i have many input fields, is there a simple way to validate price like that:
    if input(a,b,f,n…):checked then product_price=price+a+b+f+n and so on…
    There is to many variation for every statements, its good if you have 20 ;/
    Regards, Gabrielle