Finding Lowest Price in Woocommerce Cart Items - php

Wondering if anyone can help me resolve my problem here. I am looking for a way to apply a coupon code to a Single (least expensive) product item in a Cart. e.g. customer add 2 SG bats at price of 100 and 200 respectively.
I want to apply 30% coupon code to my first bat (rs 100 X .70 = 70 price) for the first bat since its a cheapest item in the cart. So customer will pay 270 rs for total purchase.
I have tried to add this coupon on the Woo commerce by product but it applies to all the products (300 X .70 = 210 price).
I tried different functions of Cart object to retrieve the each item pricing without any success.
global $woocommerce;
$lowestPrice=1000;
$myproduct_price=0;
foreach ( $cart_object->cart_contents as $key => $value ) {
$myproduct_price=$value['data']->price;
if($myproduct_price < $lowerPrice) $lowestprice=$myproduct_price;
}
this code is giving me error.

Basically there are 2 steps:
Get all cart product's price and store in one array
find minimum value from array
Complete Code: (Tested)
global $woocommerce;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$product_price[] = get_option('woocommerce_tax_display_cart') == 'excl' ? $_product->get_price_excluding_tax() : $_product->get_price_including_tax(); /*Store all product price from cart items in Array */
}
}
$lowestprice = min($product_price); // Lowest Price from array
Hope it will help you :)

Related

Woocommerce - Apply 10% discount to the lowest priced product in the cart based on several conditions

I'm struggled with one problem and the problem is as it follows. In our store users could create a package from 3 products. I need to apply a 10% discount to 2 products in cart.
PRODUCT required to get a discount = 10 euros
PRODUCT = 15 euros - you could get a discount from this product
PRODUCT = 12 euros - you could get a discount from this product
Discount should apply always to required product and the lowest price product 2 or 3.
Cart examples
If there is product 1, 2 and 3 in cart you will get a 10% discount to product number 1 and product number 3.
If there is a product number 1 and 3 in cart you will get a 10% discount to the both of them
If there is a product number 1 and 2 in cart you will get a 10% discount to the both of them
If there is a product number 1 only, product number 2 only, product number 3 only, then no discount is applied to your cart
If there is some of the combinations and other products which are not these 3 mentioned products above, the discount will be applied only for the mentioned products as it follows from cart examples above.
If there are more sets - if you want to order 2 products from (product number 1 and product number 2) or (product number 1 and product number 3) you have to add always 1 more to the both of them to get another 10% sale from another set so quantity will be 2/2. If theres quantity 2 (ID1)/1 (ID2) no discount will be applied for the second set only for the first one.
My code so far but I'm totally lost
function apply_discount_ten( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Product ID needs to be in cart to get a discount
$product_id = 2530;
// Products in cart
$products_in_cart = count( $cart->get_cart() );
//Set conditions
if ( $products_in_cart && (matched_cart_items($product_id)) {
// Set array
$product_prices = array();
// Loop though cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Product
$product = $cart_item['data'];
// Get price
$product_price = $product->get_price();
// Push
$product_prices[] = $product_price;
}
// Sort: low to high
asort( $product_prices );
// Number of products receive a discount
$products_receive_discount = What to do here;
// Set variable
$total = 0;
// Loop trough
foreach ( array_slice( $product_prices, 0, $products_receive_discount ) as $product_price ) {
// Calculate
$total += $product_price;
}
// Calculate discount
$discount = ( $total * 10 ) / 100;
// Add fee
$cart->add_fee( 'Discount', $discount, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'apply_discount_ten', 10, 1 );
Thank you in advance

WooCommerce custom code deleting item as soon as it's added to cart

I am trying to set up a custom coupon code so that customers can add an add-on product to their cart, only if their cart total is $50 or more.
I am using Allow add to cart for specific products based on cart total in WooCommerce answer code that allows or denies adding the product depending on their cart total and this is working great.
My issue is that I have another bit of code that is supposed to delete the addon item if it's in the cart and the cart total is no longer within the threshold.
In my case I have the threshold set to $50, and the addon product costs $10.
In testing I've found that when the cart total is $60 or more, everything works fine. I can even remove a couple of items from the cart and the addon item will stay until the total is under the threshold, then it gets removed as well.
However if the cart total is anywhere between $50 and $60 when I go to add the addon item, the addon item is immediately deleted as soon as it's added.
I would expect the order of operations to go
Checks the cart total, finds that it is above $50
Allows me to add the addon item
Checks the cart total with the addon item included, finds that it is now above $60
Allows the addon to stay
Based on Add or remove specific cart Item based on WooCommerce cart total answer code, here is the code I'm using:
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users (and avoiding the hook repetition)
if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 50; // The threshold amount for cart total
$addon_product_id = 7039; // ID of the addon item
$addon_product_cost = 10; // Cost of addon item
$cart_items_total = 0; // Initializing
$threshold_amount_with_addon = $threshold_amount + $addon_product_cost;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( $cart_item['data']->get_id() == $addon_product_id ) {
$addon_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If cart total is below the defined amount and addon product is in cart, we remove it.
if ( $cart_items_total < $threshold_amount_with_addon && isset($addon_item_key) ) {
$cart->remove_cart_item( $addon_item_key );
return;
}
}
I can't for the life of me figure out what is going wrong. Any help would be much appreciated.
Below, we exclude the Add-On item from subtotal calculation so we don't need to add the Add-On price to threshold amount (so we keep your steps 1, 2 and 4).
The revisited code:
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users, avoiding the hook repetition
if ( ! is_user_logged_in() || did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$addon_product_id = 7039; // ID of the addon item
$threshold_amount = 50; // The threshold amount
$cart_items_total = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// For Add-On product: Check if it is in cart
if ( in_array( $addon_product_id, [$cart_item['product_id'], $cart_item['variation_id']] ) ) {
$addon_item_key = $cart_item_key;
}
// For other items: add their line total including taxes to items subtotal
else {
// Sum dicounted line total incl. taxes to get other items subtotal
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// If cart total is below the defined amount and addon product is in cart, we remove it.
if ( $cart_items_total < $threshold_amount && isset($addon_item_key) ) {
$cart->remove_cart_item( $addon_item_key );
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Auto add a variable quantity of specific product based on WooCommerce cart subtotal

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.

Changing WooCommerce coupon discount amount in cart

What I'm doing:
I am creating a coupon based promo. The coupon will discount 10% of the most expensive item in the cart that belongs to a specific product category.
The problem:
The code below successfully checks if the cart contains products from the specific category, and obtains 10% of the price of the most expensive product from that array to use for the discount. However, I can't get the coupon discount amount to change in the cart.
The code:
function change_coupon_price_for_promo( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ){
return;
}
// coupon code
$coupon_name = 'MYCOUPONNAME';
// if coupon is applied to cart...
if( $cart->has_discount( $coupon_name ) ) {
// Form array of products from the cart that belong to the specified category
$specProduct = array(); // array of specific products in cart
foreach ( $cart->get_cart() as $key => $cart_item ) {
$cart_item_id = $cart_item['product_id'];
$terms = wp_get_post_terms( $cart_item_id, 'product_cat' );
foreach ( $terms as $term ){
// gets product cat id
$product_cat_id = $term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
if(in_array(3831, $last_parent_cat)){
$specProduct[$key] = $cart_item_id;
break;
}
}
}
//if there are items from the specific category in the cart
if(!empty($specProduct)){
$specPriceArray = array(); // array of specific product prices in cart
foreach ($specProduct as $key => $specItem) {
$thisProd = wc_get_product($specItem);
$thisPrice = $thisProd->get_price();
$specPriceArray[$key] = $thisPrice;
}
// most expensive specific product price
$highestSpec = max($specPriceArray);
// discount of most expensive item
$finalDiscount = $highestSpec * .1;
// print_r($specProduct); GOOD
// print_r($specPriceArray); GOOD
// echo $highestSpec; GOOD
// echo $finalDiscount; GOOD
/***** APPLY COUPON CHANGE HERE<-------HOW??? *****/
$cart->discount_total = $finalDiscount;
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'change_coupon_price_for_promo', 10, 1 );
What I'm asking:
The last line of the code before the closing brackets...
$cart->discount_total = $finalDiscount;
is what I tried using to change the coupon's discount in the cart. It doesn't work. How can I accomplish this? TY.
EDIT:
I should note that the coupon being added is set up as a "Fixed cart discount" with a rate of 0 so it is added as a line item to the order. This way the user sees the discount for the coupon code on its own line in the cart/checkout.
you can use function set_price.
you can call it in your code like:
$cart_item['data']->set_price('New price here')
use this inside the foreach that loops your cart items

woocomerce calculate final price based on the quantity of one product

I am currently setting up a woocommerce shop. Basically this is what I am trying to achieve.
"this is a fruit shop for whom they want fruits in basket( package), the customer select the fruits he wants (for example 3 items), then he/she select the basket with the desired quantity (1 among 3 different baskets in sites).
the total cost must be calculated like this: {sum(fruit a+fruit b+fruit c+basket price)* (the quantity of selected basket).
for example: apple price 3$, banana price 3$, selected basket price 1$, quantity of basket is: 200. total cost=(3+3+1)*200.
so this is just an example as I would like to setup pricing.
any idea how can that be achieved, I tried multiple plugins recommended by woocommerce but non of them do what I am looking for.
your help is greatly appreciated...
i write the following code for (in this code basket product id is 24).
But the problem is when I set for ex: 10 for basket. the total cost at the end of basket line in cart page exactly at the end of basket row will be like this: basket quantity* basket cost of 1$ so this is here 10 $.
And the total price is (3$ for bababa+3$ for apple+10 $ of basket )* QUANTITY of basket.
The right calculation is (3+3+1)*10.
add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {
$targeted_id = 24;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if($cart_item['product_id'] == $targeted_id ){
$qty = $cart_item['quantity'];
break; // stop the loop if product is found
}
}
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( !WC()->cart->is_empty() ):
$cart_object->subtotal *= $qty;
$cart_object->total *= $qty;
$cart_object->cart_contents_total *= $qty;
endif;
}
It seems your problem falls under Custom price calculation category.
There are some wordpress plugins you may get the job done by them like WooPrice Calculator and Booster for WooCommerce.

Categories