I am currently creating my first site using woocommerce for a client, and they are requesting for me to have a price increase per variation and quantity, however i am not sure how to do it. Here is an example of what they are asking for:
Product Type: Limestone
Variations:
Product Size:
10kg bag
20kg bag
40kg bag
Quantity:
1-20
TL;DR
if the customer wants multiple 10kg bags, the price increases by £36 at a time, if they want multiple 20kg bags, the price increases by £30 at a time, and if they want multiple 40kg bags, the price doubles every time.
I have used woocommerce variations and attributes so far but now it would require modifying having 3x20 variations all of which require a different price, which would be easier to change if a statement is possible as follows:
if ($productsize === '10kg') {
$quantity = 2; //get quantity from textbox $_POST
$initial_price = 36; //get inital price from woocommerce global variable
$total_price = $inital_price * $quantity;
update_price($total_price); //a function to update the price in woocommerce when adding to cart
}
Obviously the code above does not use any woocommerce variables, however doing this for only 3 variations would be easier than manually entering 60 variations on one product for which we have >60 on our site.
I don't know if you need it anymore, however try it
add_action( 'woocommerce_before_calculate_totals', 'IG_recalculate_price',5,1 );
function IG_recalculate_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$quantity = 0;
foreach ( $cart_object->get_cart() as $key => $value ) {
// count q.ty
$quantity += $value['quantity'];
// delta q.ty
if( $quantity > 24 ) {
// get price by custom field but you can use a simple var
$newprice = get_post_meta( $value['data']->get_id(), 'custom_field2', true);
$value['data']->set_price( $newprice );
// reset q.ty for check every item in the cart
$quantity = 0;
}else{
$newprice = get_post_meta( $value['data']->get_id(), 'custom_field', true);
$value['data']->set_price( $newprice );
$quantity = 0;
}
}
}
Related
I'm trying to add a gift product to a shopping cart based upon the total cost spent by a customer. It's for a restaurant that sells gift vouchers.
The scheme runs as follows: for every £50 that a customer spends in a single transaction, they automatically receive a £10 gift voucher for free. So, if they spend £100 on gift vouchers, they receive 2x £10 gift vouchers for free (and so on).
To keep things as simple as possible, we're limiting denominations of gift vouchers (£25 - £250 increasing in £25 denominations).
I don't particularly want to pay for/install another plugin that will need to be updated/managed, etc. If I'm honest, it's only for the Christmas period so a snippet of code to do this would be far better.
The way I see it working is that a customer adds the vouchers to the cart and when they go to the cart it shows they've also got the additional 'free' vouchers in there too.
I've found some code online and made some changes to it. The code is as follows:
function auto_add_specific_product_to_cart() {
// select product ID
$product_id = 1428;
// if cart empty, add it to cart
if ( WC()->cart->get_cart_total() <= 99 ) {
WC()->cart->add_to_cart( $product_id, 1 ); }
else if ( WC()->cart->get_cart_total() <= 149 ) {
WC()->cart->add_to_cart( $product_id, 2 ); }
else if ( WC()->cart->get_cart_total() <= 199 ) {
WC()->cart->add_to_cart( $product_id, 3 ); }
else if ( WC()->cart->get_cart_total() <= 249 ) {
WC()->cart->add_to_cart( $product_id, 4 ); }
}
I'm having problems with it right, left and centre. It keeps adding the free vouchers to the shopping cart so eventually customers end up with 20 or 30 vouchers there; the PHP for recognising the different thresholds (50 to 99, 100 to 149, etc) aren't working properly. I'm probably making this far too complicated and not thinking it through but a bit of help would be great.
I've found plenty of code online for discounting products but nothing that gives something away for free.
Here a variable quantity of a "specific product voucher" will be auto added to cart based on cart subtotal.
The code below is based on Add free gifted product for a minimal cart amount in WooCommerce answer code. The code automate the generation of cart subtotal thresholds (min and max amounts) and the related quantity of the voucher product to be added to cart.
The number set in $max_quantity variable, determines the number of iterations on the FOR loop (so the number of different generated thresholds and the max quantity of voucher product that can be added to cart).
// Auto add a quantity of voucher product based on cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'auto_add_voucher_product_based_on_subtotal' );
function auto_add_voucher_product_based_on_subtotal( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Settings
$voucher_product_id = 37; // Voucher product Id
$max_quantity = 20; // Here set the max item quantity (for voucher product)
$min_subtotal = 50; // Starting threshold min amount
$cart_subtotal = 0; // Initializing
// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// When voucher product is is cart
if ( $voucher_product_id == $cart_item['product_id'] ) {
$voucher_key = $cart_item_key;
$voucher_qty = $cart_item['quantity'];
// $cart_item['data']->set_price(0); // (optional) set the price to zero
} else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax']; // Get subtotal
}
}
// If voucher product is not already in cart, add it
if ( ! isset($voucher_key) && $cart_subtotal >= $min_subtotal ) {
$cart->add_to_cart( $voucher_product_id );
}
// Check vouvher product quantity and adjust it depending on the subtotal amount.
else {
// Loop dynamically through subtotal threshold min and max amounts setting the right quantity
// $i is the min amount, $j the max amount and $q the related quantity to check
for ( $i = $min_subtotal, $j = 100, $q = 1; $q < $max_quantity; $i += 50, $j += 50, $q++ ) {
if ( $cart_subtotal >= $i && $cart_subtotal < $j && $voucher_qty != $q ) {
$cart->set_quantity( $voucher_key, $q );
}
}
if ( $cart_subtotal >= $i && $voucher_qty != $q ) {
$cart->set_quantity( $voucher_key, $q );
}
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
A friends ask me to add an extra fee on cart based on weight and only for specific categories (or excluding some categories, it doesn't matters).
The topic is, for summer, he wants to add ice into the packages to keep the products cold (ex. milk, cheese, etc).
He sells also gadgets and guided visits to his factory, etc so he doesn't want to apply the extra fee to those products.
Based on "Add custom fee based on total weight in Woocommerce" answer, my code version below, apply an extra fee to the whole cart, excluding the visit-product from this fee because the weight of the visit is obviously 0.
But I am not an expert with code and I don't know how to insert an array to include categories like 'milk' and 'cheese' (or viceversa to exclude 'visits' and 'gadgets').
In addiction, my code increase the fee by steps of 3kg (due to sizing of the packets by DHL/UPS/GLS etc)
/* Extra Fee based on weight */
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Convert in grams
$cart_weight = $cart->get_cart_contents_weight() * 1000;
$fee = 0.00; // initial fee
// if cart is > 0 add €1,20 to initial fee by steps of 3000g
if( $cart_weight > 0 ){
for( $i = 0; $i < $cart_weight; $i += 3000 ){
$fee += 1.20;
}
}
// add the fee / doesn't show extra fee if it's 0
if ( !empty( $fee )) {
$cart->add_fee( __( 'Extra for ice' ), $fee, false );
}
}
Last question is: why the $i variable could be 0...1...1000000 without any change in the results? the code seems working exactly the same...
thanks
The following code is based on:
Predefined categories
Based on product weight (of products belonging to the predefined categories)
Fee increases by steps
(comment with explanation added in the code)
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
/* SETTINGS */
// Specific categories
$specific_categories = array( 'categorie-1', 'categorie-2' );
// Initial fee
$fee = 1.20;
// Steps of kg
$steps_of_kg = 3;
/* END SETTINGS */
// Set variable
$total_weight = 0;
// Loop though each cart item
foreach ( $cart->get_cart() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Get weight
$product_weight = $cart_item['data']->get_weight();
// NOT empty & has certain category
if ( ! empty( $product_weight ) && has_term( $specific_categories, 'product_cat', $product_id ) ) {
// Quantity
$product_quantity = $cart_item['quantity'];
// Add to total
$total_weight += $product_weight * $product_quantity;
}
}
if ( $total_weight > 0 ) {
$increase_by_steps = ceil( $total_weight / $steps_of_kg );
// Add fee
$cart->add_fee( __( 'Extra for ice' ), $fee * $increase_by_steps, false );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 10, 1 );
In WooCommerce, I would like to make a discount without using coupons, and the discount calculation will be based on product price, with something like "take 3 products for the price of 2.
In function.php of my active theme I am using this code:
function promo () {
if (is_cart()) {
$woocommerce->cart->add_fee( __('des', 'woocommerce'), -50.00`enter code here`, true, '');
}
}
add_action ('woocommerce_cart_calculate_fees', 'promo');
My problem: This code doesn't work on checkout page.
If I force in review-order the discount appears, but the total value don't change. I think its not saving the fee.
How can I make it work (on checkout page)?
Thanks
This hook is made for cart fees (or discounts), so you have to remove if (is_cart()) { condition, that why it's not working…
Here is the correct functional code to achieve a "Buy 2 take 3" discount, that will make a discount based on line item quantity:
add_action('woocommerce_cart_calculate_fees' , 'discount_2_for_3', 10, 1);
function discount_2_for_3( $cart_object ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising variable
$discount = 0;
// Iterating through cart items
foreach( $cart_object->get_cart() as $cart_item ){
// Getting item data from cart object
$item_id = $cart_item['product_id']; // Item Id or product ID
$item_qty = $cart_item['quantity']; // Item Quantity
$product_price = $cart_item['data']->price; // Product price
$line_total = $cart_item['line_total']; // Price x Quantity total line item
// THE DISCOUNT CALCULATION
if($item_qty >= 3){
// For each item quantity step of 3 we add 1 to $qty_discount
for($qty_x3 = 3, $qty_discount = 0; $qty_x3 <= $item_qty; $qty_x3 += 3, $qty_discount++);
$discount -= $qty_discount * $product_price;
}
}
// Applied discount "2 for 3"
if( $discount != 0 ){
// Note: Last argument is related to applying the tax (false by default)
$cart_object->add_fee( __('Des 2 for 3', 'woocommerce'), $discount, false);
}
}
This will work for simple products, but not for product variations…
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested and works.
I'm in a unique situation with my Woocommerce site.
I need to add a packaging fee, which will be somewhat similar to a handling fee.
Unfortunately, it's not as simple as adding a $5.00 handling fee to every order.
Since I sell wood products based on their measurements (width x height), the packaging fees are based on the total square footage for items. And they can differ depending on the category of the items, as well.
I've done a ton of research and I can't find a plugin to handle this situation.
To add to the complexity, there's a whole table that would need to be created. For example, if items from one category have a total square footage between 1-10, then the packaging fee will be $10. If total sq ftg is between 11-20, then it'll be $20.
How can I do to achieve that?
Thanks
Updated: Added WooCommerce 3+ compatibility
This is possible and easy with the add_fee() method in the woocommerce_cart_calculate_fees hook. Here is a simple usage example for simple products, with 2 categories and based on the product dimensions measurement calculations for each item of the cart. Its also possible for other product types.
Here is the example code (That you will need to customize for your own case):
add_action( 'woocommerce_cart_calculate_fees','custom_applied_fee', 10, 1 );
function custom_applied_fee( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your categories (can be an ID, a slug or the name… or an array of this)
$category1 = 'plain';
$category2 = 'plywood';
// variables initialisation
$fee = 0;
$coef = 1;
// Iterating through each cart item
foreach( $cart_object->get_cart() as $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
$product = $cart_item['data']; // Get the product object
// Get the dimentions of the product
$height = $product->get_height();
$width = $product->get_width();
// $length = $product->get_length();
// Initialising variables (in the loop)
$cat1 = false; $cat2 = false;
// Detecting the product category and defining the category coeficient to change price (for example)
// Set here for each category the modification calculation rules…
if( has_term( $category1, 'product_cat', $cart_item['product_id']) )
$coef = 1.15;
if( has_term( $category2, 'product_cat', $cart_item['product_id']) )
$coef = 1.3;
// ## CALCULATIONS ## (Make here your conditional calculations)
$dimention = $height * $with;
if($dimention <= 10){
$fee += 10 * $coef;
} elseif($dimention > 10 && $dimention <= 20){
$fee += 20 * $coef;
} elseif($dimention > 20){
$fee += 30 * $coef;
}
}
// Set here the displayed fee text
$fee_text = __( 'Packaging fee', 'woocommerce' );
// Adding the fee
if ( $fee > 0 )
WC()->cart->add_fee( $fee_text, $fee, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
You will have to set your own categories with the related changes calculations for each category. You will get a non detailed general output fee calculated taking into account each item in the cart.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
The code is tested and fully functional.
Related Answers:
Discount for Certain Category Based on Total Number of Products
Cart discount for a product category based on quantity calculations
In WooCommerce, I have a category of products called Samples, each sample costs $2.99.
But I'd like a way to automatically change the cost of the Samples from $2.99 to $1 when 5 Samples are added to cart.
So if 4 samples are added to cart, the total would be $11.96… but if 5 were added the total would be $5.
So for every 5 products, the product price would change from $2.99 to $1 but if 6 Samples were added to cart the total would be $7.99 and if 10 were added the total would be $10 etc...
How could I achieve this?
Thanks.
Update — Added Woocommerce 3 compatibility.
Here is something that should be convenient to your requirements.
This function will add discount to cart:
add_action( 'woocommerce_cart_calculate_fees','custom_cart_discount', 20, 1 );
function custom_cart_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Define HERE your targeted product category (id, slug or name are accepted)
$category = 'posters';
// Set the price for Five HERE
$price_x5 = 5;
// initializing variables
$calculated_qty = 0;
$calculated_total = 0;
$discount = 0;
// Iterating through each cart item
foreach($cart->get_cart() as $cart_item):
// Make this discount calculations only for products of your targeted category
if(has_term($category, 'product_cat', $cart_item['product_id'])):
$item_price = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->price : $cart_item['data']->get_price(); // The price for one (assuming that there is always 2.99)
$item_qty = $cart_item["quantity"];// Quantity
$item_line_total = $cart_item["line_total"]; // Item total price (price x quantity)
$calculated_qty += $item_qty; // ctotal number of items in cart
$calculated_total += $item_line_total; // calculated total items amount
endif;
endforeach;
// ## CALCULATIONS (updated) ##
if($calculated_qty >= 5):
for($j = 5, $k=0; $j <= $calculated_qty; $j+=5,$k++); // Update $k=0 (instead of $k=1)
$qty_modulo = $calculated_qty % 5;
$calculation = ( $k * $price_x5 ) + ($qty_modulo * $item_price);
$discount -= $calculated_total - $calculation;
endif;
// Adding the discount
if ($discount != 0)
$cart->add_fee( __( 'Quantity discount', 'woocommerce' ), $discount, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.