Woocommerce: add free product if cart has 3 items - php

What I'm trying to do is to add free product if user have 3 product in cart.
I choosed woocommerce_add_cart_item hook for this.
Here is my code :
add_filter('woocommerce_add_cart_item', 'set_item_as_free', 99, 1);
function set_item_as_free($cart_item) {
global $woocommerce;
$products_with_price = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if($values['data']->price == 0) {
continue;
} else {
$products_with_price++;
}
}
if( $products_with_price > 1 && $products_with_price % 3 == 1) {
$cart_item['data']->set_price(0);
return $cart_item;
}
return $cart_item;
}
I also tried $cart_item['data']->price = 0; but it doesn't work out either :(
Is there is something I do wrong or maybe there is some other way to get this done?
Thanks.

Try this modified code: (Have changed the condition.)
add_filter('woocommerce_add_cart_item', 'set_item_as_free', 99, 1);
function set_item_as_free($cart_item) {
global $woocommerce;
$products_with_price = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if($values['data']->price == 0) {
continue;
} else {
$products_with_price++;
}
}
if( $products_with_price >= 3 && $products_with_price % 3 == 1) {
$cart_item['data']->set_price(0);
return $cart_item;
}
return $cart_item;
}
If you don't want to add a free product again after a user purchases another 3 products above the existing cart then remove " && $products_with_price % 3 == 1" from the last condition.

Do not use the woocommerce_add_cart_item hook to set the price of the product, a lot of plugin like to refetch the price of the product in the database in the hook woocommerce_before_calculate_totals (that's the case of WPML/WCML)
So instead use this hook
add_action( 'woocommerce_before_calculate_totals', function ( $cart_obj ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Avoiding hook repetition (when using price calculations for example)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) {
return;
}
// Loop through cart items
foreach ( $cart_obj->get_cart() as $cart_item ) {
if ( isset( $cart_item['free_item'] ) ) {
$cart_item['data']->set_price( 0 );
}
}
} );

Related

Show cash on delivery (COD) based on applied coupons in WooCommerce

I am trying to have cash on delivery (COD) enabled only for customers that use certain type off coupons.
I have an existing code that, when coupons of a certain type are entered, converts the product sales price to the regular product price.
Now I would like to add that cash on delivery (COD) only is available for valid coupons within the same function.
The part that I have tried to add is this:
if ($coupons = WC()->cart->get_applied_coupons() == False )
unset( $available_gateways['cod'] );
Resulting in:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object) {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon = False;
if ($coupons = WC()->cart->get_applied_coupons() == False )
unset( $available_gateways['cod'] );
if ($coupons = WC()->cart->get_applied_coupons() == False )
$coupon = False;
else {
foreach ( WC()->cart->get_applied_coupons() as $code ) {
$coupons1 = new WC_Coupon( $code );
if ($coupons1->type == 'percent_product' || $coupons1->type == 'percent')
$coupon = True;
}
}
if ($coupon == True)
foreach ( $cart_object->get_cart() as $cart_item )
{
$price = $cart_item['data']->regular_price;
$cart_item['data']->set_price( $price );
}
}
This does not give real error messages, but certainly not the desired result either. Any advice?
First of all I have rewritten your existing code, the part that converts sale prices to regular prices when a certain type of coupon is applied. This because your current code contains outdated methods:
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Initialize
$flag = false;
// Applied coupons only
if ( sizeof( $cart->get_applied_coupons() ) >= 1 ) {
// Loop trough
foreach ( $cart->get_applied_coupons() as $coupon_code ) {
// Get an instance of the WC_Coupon Object
$coupon = new WC_Coupon( $coupon_code );
// Only for certain types, several can be added, separated by a comma
if ( in_array( $coupon->get_discount_type(), array( 'percent', 'fixed_product', 'percent_product' ) ) ) {
$flag = true;
break;
}
}
}
// True
if ( $flag ) {
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get regular price
$regular_price = $cart_item['data']->get_regular_price();
// Set new price
$cart_item['data']->set_price( $regular_price );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
Then to only make COD active, if coupons of a certain type are applied you can use the woocommerce_available_payment_gateways hook
By default COD will not be available:
// Payment gateways
function filter_woocommerce_available_payment_gateways( $payment_gateways ) {
// Not on admin
if ( is_admin() ) return $payment_gateways;
// Initialize
$flag = false;
// WC Cart
if ( WC()->cart ) {
// Get cart
$cart = WC()->cart;
// Applied coupons only
if ( sizeof( $cart->get_applied_coupons() ) >= 1 ) {
// Loop trough
foreach ( $cart->get_applied_coupons() as $coupon_code ) {
// Get an instance of the WC_Coupon Object
$coupon = new WC_Coupon( $coupon_code );
// Only for certain types, several can be added, separated by a comma
if ( in_array( $coupon->get_discount_type(), array( 'percent', 'fixed_product', 'percent_product' ) ) ) {
$flag = true;
break;
}
}
}
}
// NOT true, so false
if ( ! $flag ) {
// Cod
if ( isset( $payment_gateways['cod'] ) ) {
unset( $payment_gateways['cod'] );
}
}
return $payment_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'filter_woocommerce_available_payment_gateways', 10, 1 );
Both codes go goes in functions.php file of the active child theme (or active theme).
Tested in WordPress 5.8.1 and WooCommerce 5.8.0

Increase cart item prices based on payment method in WooCommerce

I want to add percentage value to cart item prices based on the selected payment gateway.
The problem I am facing is variation product price is not updating for the product price. Initially selected price is showing all the time.
How can I get the changed price accordingly?
My code so far:
// Set custom cart item price
function add_custom_price( $cart ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetition (when using price calculations for example | optional)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
$chosen_payment_method = WC()->session->get('chosen_payment_method');
if($chosen_payment_method == 'cod') {
$increaseby = 3;
} elseif($chosen_payment_method == 'paypal') {
$increaseby = 8;
} else {
$increaseby = 10;
}
$price = get_post_meta($cart_item['product_id'] , '_price', true);
$price = $price + (($price * $increaseby)/100);
$cart_item['data']->set_price( $price );
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
Any help highly appreciated.
There are some mistakes in your code
Use WC()->session->get( 'chosen_payment_method' ); outside the foreach loop
get_post_meta() is not needed to get the price, you can use get_price()
You will also need jQuery that is triggered when changing the payment method.
So you get:
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Get payment method
$chosen_payment_method = WC()->session->get( 'chosen_payment_method' );
// Compare
if ( $chosen_payment_method == 'cod' ) {
$increaseby = 3;
} elseif ( $chosen_payment_method == 'paypal' ) {
$increaseby = 8;
} else {
$increaseby = 10;
}
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get price
$price = $cart_item['data']->get_price();
// Set price
$cart_item['data']->set_price( $price + ( $price * $increaseby ) / 100 );
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
function action_wp_footer() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery(function($){
$( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function() {
$(document.body).trigger( 'update_checkout' );
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'action_wp_footer' );

WooCommerce custom Ajax add to cart: How to set a custom price?

I am trying to add a product from an on_click event at checkout.
That product's price is calculated dynamically with an external API so it is registered as having a price of 0 in woocommerce itself. I am trying to add this product to the cart (working) and then set that product's price to the one I receive from the API (not working). Here is the relevant code:
AJAX call on click:
jQuery('#theftdaminsurance').on('click', function(){
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'add_product_to_cart_checkout',
// add your parameters here
price: <?php echo $year_dam_price; ?>,
productid: ins_product_id
},
success: function (output) {
document.getElementById("loaderdiv").style.display = "none";
jQuery(document.body).trigger("update_checkout");
}
});
});
I checked everything here and the call is made properly with all the right info being passed on.
Here is the function being called:
add_action('wp_ajax_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
// register the ajax action for unauthenticated users
add_action('wp_ajax_nopriv_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
function add_product_to_cart_checkout() {
$product_id = $_REQUEST['productid'];
$price = floatval($_REQUEST['price']);
$ebike_ids = array(17386,17385,17382,17378,17375,17372,17370,17369,17364,16132,16130,4561,4550,3490,2376);
$found = false;
//check if there is something in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
//Delete all preexisting insurance products and find qty of ebikes
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_idebike = $cart_item['product_id'];
if ( ($cart_item['product_id'] == "16600") || ($cart_item['product_id'] == "16653") || ($cart_item['product_id'] == "16654") || ($cart_item['product_id'] == "16655") ||($cart_item['product_id'] == "16659") || ($cart_item['product_id'] == "16660")) {
WC()->cart->remove_cart_item( $cart_item_key );
}
//get ebike quantity
for ($x = 0; $x <= 14; $x++) {
if ($product_idebike == $ebike_ids[$x]) {
$quantity = $cart_item['quantity'];
break;
}
}
}
// if command is not to remove add relevant products
if ($price != "-1") {
WC()->cart->add_to_cart( $product_id, $quantity );
foreach( WC()->cart->get_cart() as $cart_item ){
$id = $cart_item['product_id'];
if ($product_id == $id) {
$cart_item['data']->set_price( $price );
}
}
}
}
}
Here I basically debugged everythingcarefully and everything behaves as it should but the set_price function. I cannot get it to update the product's price to the one passed in the AJAX call. The price remains 0 once the checkout is updated and before it is as well. Am i calling or using this function the wrong way?
Thanks a lot for your help!
It seems that you are making things much more complicated than they should be on your Ajax receiver function…
Note that you can add custom cart item data when using WC_Cart add_to_cart() method, so you will add your insurance price as custom cart item data and afterwards use it to set the price.
Here is your revisited Ajax PHP receiver function:
add_action('wp_ajax_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
add_action('wp_ajax_nopriv_add_product_to_cart_checkout', 'add_product_to_cart_checkout');
function add_product_to_cart_checkout() {
if ( isset($_POST['productid']) && isset($_POST['price']) && ! WC()->cart->is_empty() ) {
$product_id = intval($_POST['productid']);
$price = floatval($_POST['price']);
$ebike_ids = array(17386,17385,17382,17378,17375,17372,17370,17369,17364,16132,16130,4561,4550,3490,2376);
$insurance_ids = array(16600,16653,16654,16655,16659,16660);
$found = false;
$ebike_quantity = 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Delete all preexisting insurance products
if ( in_array( $cart_item['product_id'], $insurance_ids ) ) {
WC()->cart->remove_cart_item( $cart_item_key );
}
// Get ebikes total quantity
if ( in_array( $cart_item['product_id'], $ebike_ids ) ) {
$ebike_quantity += $cart_item['quantity'];
}
}
// If command is not to remove add insurance product with price as custom cart item data
if ( $price >= 0 && $cart_item['insurance_price'] > 0 ) {
WC()->cart->add_to_cart( $product_id, $ebike_quantity, 0, array(), array( 'insurance_price' => $price ) );
}
die();
}
}
Then to set the price you will use:
// Set insurance price from custom cart item data
add_action( 'woocommerce_before_calculate_totals', 'set_insurance_price' );
function set_insurance_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cart_item['insurance_price']) && $cart_item['insurance_price'] > 0 ) {
$cart_item['data']->set_price( $cart_item['insurance_price'] );
}
}
}
Now It should works.

WooCommerce discount: buy one get one 50% off with a notice

After my previous question WooCommerce discount: buy one get one 50% off I want to add custom notice to the cart, whenever a particular product(not all the products) gets added to the cart.
I want to check the quantity first, if it's 1 then I want to display a notice to increase the quantity of that product. I have figured something by myself from the internet and I don't think my solution is right:
add_action( 'wp', 'sp_custom_notice' );
function sp_custom_notice() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
//to display notice only on cart page
if ( ! is_cart() ) {
return;
}
global $product;
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
if($product_id == 15730){
//check for quantify if equal to 1 in cart
wc_clear_notices();
wc_add_notice( __("Add one more to get 50% off on 2nd product"), 'notice');
}
}
It will be great if anyone can help me on this.
Updated July 2020
If you are still using the code from my answer to your previous question, you can change it a bit to get this working too:
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );
function add_custom_discount_2nd_at_50( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// YOUR SETTINGS:
$targeted_product_id = 40; // Set HERE your targeted product ID
// Initializing variables
$discount = $qty_notice = 0;
$items_prices = array();
// Loop through cart items
foreach ( $cart->get_cart() as $key => $cart_item ) {
if( in_array( $targeted_product_id, [$cart_item['product_id'], $cart_item['variation_id']] ) ){
$quantity = (int) $cart_item['quantity'];
$qty_notice += $quantity;
for( $i = 0; $i < $quantity; $i++ ) {
$items_prices[] = floatval( $cart_item['data']->get_price());
}
}
}
$count_items = count($items_prices); // Count items
rsort($items_prices); // Sorting prices descending order
if( $count_items > 1 ) {
foreach( $items_prices as $key => $price ) {
if( $key % 2 == 1 )
$discount -= number_format( $price / 2, 2 );
}
}
// Applying the discount
if( $discount != 0 ){
$cart->add_fee('Buy one get one 50% off', $discount );
// Displaying a custom notice (optional)
wc_clear_notices(); // clear other notices on checkout page.
if( ! is_checkout() ){
wc_add_notice( __("You get 50% of discount on the 2nd item"), 'notice');
}
}
// Display a custom notice on cart page when quantity is equal to 1.
elseif( $qty_notice == 1 ){
wc_clear_notices(); // clear other notices on checkout page.
if( ! is_checkout() ){
wc_add_notice( __( "Add one more to get 50% off on 2nd item" ), 'notice');
}
}
}
Code goes in functions.php file of your active child theme (or active theme) Tested and works.
Note: The wc_add_notice() function absolutely don't need to be echoed
You did pretty good code some minor changes are required try below code :
add_action('woocommerce_before_cart', 'sp_custom_notice');
function sp_custom_notice() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
//to display notice only on cart page
if ( ! is_cart() ) {
return;
}
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
if($values['data']->get_id() == 190 && $values['quantity'] == 1 ){
wc_clear_notices();
echo wc_add_notice( __("Add one more to get 50% off on 2nd product"), 'notice');
}
}
}

Change price of product in WooCommerce cart and checkout

I'm creating a WooCommerce add-on to customize the product, based on selected options by the visitor and custom price is calculated and stored into session table also.
I am able to get that value in cart page also.
My problem: I would like to change the default price of the product and replace it with new calculated value in the WooCommerce process as cart, checkout, payment, mail notifications, order...
Any advice please?
Thanks
Ce right hook to get it working is woocommerce_before_calculate_totals. But you will have to complete (replace) the code to get the new price in the hooked function below:
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop Through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get the product id (or the variation id)
$product_id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = 500; // <== Add your code HERE
// Updated cart item price
$cart_item['data']->set_price( $new_price );
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works on WooCommerce versions 3+. But as you don't give any code I can't test it for real getting the new price from session…
function save_subscription_wrap_data( $cart_item_data, $product_id ) {
$include_as_a_addon_subscription = get_field('include_as_a_addon_subscription',$product_id);
$subscricption_product_data = get_field('subscricption_product',$product_id);
$current_user = is_user_logged_in() ? wp_get_current_user() : null;
$subscriptions = wcs_get_users_subscriptions( $current_user->ID );
if($include_as_a_addon_subscription == "yes")
{
foreach ( $subscriptions as $subscription_id => $subscription ) {
$subscription_status = $subscription->get_status();
}
if($subscription_status == 'active')
{
$cart_item_data[ "subscribe_product" ] = "YES";
}
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'save_subscription_wrap_data', 99, 2 );
function render_meta_on_cart_and_checkout1( $cart_data, $cart_item = null ) {
$meta_items = array();
if( !empty( $cart_data ) ) {
$meta_items = $cart_data;
}
if( isset( $cart_item["subscribe_product"] ) ) {
$meta_items[] = array( "name" => "Product Type", "value" => "Package Addon" );
}
return $meta_items;
}
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout1', 100, 2 );
function calculate_gift_wrap_fee( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
$additionalPrice = 100;
foreach ( WC()->cart->get_cart() as $key => $value ) {
if( isset( $value["subscribe_product"] ) ) {
if( method_exists( $value['data'], "set_price" ) ) {
$orgPrice = floatval( $value['data']->get_price() );
//$value['data']->set_price( $orgPrice + $additionalPrice );
$value['data']->set_price(0);
} else {
$orgPrice = floatval( $value['data']->price );
//$value['data']->price = ( $orgPrice + $additionalPrice );
$value['data']->price = (0);
}
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_gift_wrap_fee', 99 );

Categories