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

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

Related

Add fee for certain products in WooCommerce cart

I have a working script that adds a fee for certain products in an array.
But it only adds the fee for the first product in the array.
I have tried different options with my knowledge but it doesn't work. Any advice on what i'm doing wrong?
This is the code:
/* Add fee to specific product*/
add_action('woocommerce_cart_calculate_fees', 'statie_geld');
function statie_geld() {
if (is_admin() && !defined('DOING_AJAX')) {return;}
foreach( WC()->cart->get_cart() as $item_keys => $item ) {
$quantiy = $item['quantity']; //get quantity from cart
if( in_array( $item['product_id'], statiegeld_ids() )) {
WC()->cart->add_fee(__('Statiegeld Petfles 24'), 3.60 * $quantiy );
}
}
}
function statiegeld_ids() {
return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 );
}
Your code contains some mistakes
No need to use WC()->cart, $cart is passed to the function
$quantiy is overwritten on each loop
Same for adding the fee, this is overwritten on each loop
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Initialize
$quantity = 0;
// Loop though each cart item
foreach ( $cart->get_cart() as $cart_item ) {
// Compare
if ( in_array( $cart_item['product_id'], statiegeld_ids() ) ) {
// Addition
// Get product quantity in cart
$quantity += $cart_item['quantity'];
}
}
// Greater than
if ( $quantity > 0 ) {
// Add fee
$cart->add_fee( __( 'Statiegeld Petfles 24', 'woocommerce' ), 3.60 * $quantity );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
// Specify the product IDs
function statiegeld_ids() {
return array( 4535, 4537, 89694, 89706, 3223, 4742, 14846, 26972, 32925, 32927, 32929, 37475 );
}

Custom cart item price when applying coupon for a category in Woocommerce

We have some products in shop , and we are giving some coupons to customer .
product -> ABC price 10
coupon code is 'newcp' discount 20%;
so when people add the product to cart price will be 10 .
Then they apply coupon then original product price shown as 10 and calculate 20% from that and at the end the total will be 8
But now we need to change this as per specific condition
When people apply product coupon newbc
1)if coupon is newcp , then change order_item_price as order_item_price +3[ only if category is Fruit] , and this price should be shown in cart page, checkout page , order email
2)Calculate discount from the new price calculate discouunt from 13
3)If people remove coupon then price will again return to 10
I made 2 solutions , but not working.
Solution 1
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price($cart_obj)
{
if (is_admin() && !defined('DOING_AJAX')) return;
foreach($cart_obj->get_cart() as $key => $value)
{
$product_id = $value['product_id'];
$coupon_code = $value['coupon_code'];
if ($coupon_code != '' && $coupon_code == "newcp")
{
global $woocommerce;
if (WC()->cart->has_discount($coupon_code)) return;
else
{
if (has_term('fruits', 'product_cat', $product_id))
{
$value['data']->set_price(CURRENT_CART_PRICE + 3);
}
}
}
}
}
Solution 2
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 )
$coupon = False;
else {
foreach ( WC()->cart->get_applied_coupons() as $code ) {
$coupon = $code;
}
}
if ($coupon == "newcp"){
foreach ( $cart_object->get_cart() as $cart_item )
{
$price = $cart_item['data']->price+3;
$cart_item['data']->set_price( $price );
}
}
}
Please help .
Here is a possible way to achieve that:
// Add custom calculated price conditionally as custom data to cart items
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 2 );
function custom_add_cart_item_data( $cart_item_data, $product_id ){
// Your settings below
$product_categories = array('fruits');
$addition = 3;
$product = wc_get_product($product_id);
$the_id = $product->is_type('variation') ? $product->get_parent_id() : $product_id;
if ( has_term( $product_categories, 'product_cat', $the_id ) )
$cart_item['custom_price'] = $product->get_price() + $addition;
return $cart_item;
}
// Set conditionally a custom item price
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 20, 1);
function add_custom_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Only for a DEFINED coupon code ( to be set below )
$coupon_code = 'newcp';
if ( ! $cart->has_discount( $coupon_code ) ) return;
foreach( $cart->get_cart() as $cart_item ) {
if ( isset($cart_item['custom_price']) ) {
$cart_item['data']->set_price( (float) $cart_item['custom_price'] );
}
}
}
Code goes in function.php file of the active child theme (or active theme). Tested and works.

Set Woocommerce cart item price to zero if the product has already been bought

I am unable to override price on second time purchase.
The use case would be: If a user has already bought product "944" then the price would be 0 for next time orders.
Meaning, the customer would pay only for first order of that specific product and it would be free for next orders.
Here my code:
// Enter the ID of the product that shouldn't be purchased again
$no_repeats_id = 944;
$no_repeats_product = wc_get_product( $no_repeats_id );
// Get the current product to check if purchasing should be disabled
global $product;
if ( $no_repeats_product->is_type( 'variation' ) ) {
// Bail if we're not looking at the product page for the non-purchasable product
if ( ! $no_repeats_product->parent->id === $product->id ) {
return;
}
// Render the purchase restricted message if we are
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $no_repeats_id ) ) {
sv_render_variation_non_purchasable_message( $product, $no_repeats_id );
}
} elseif ( $no_repeats_id === $product->id ) {
if ( wc_customer_bought_product( wp_get_current_user()->user_email, get_current_user_id(), $no_repeats_id ) ) {
// Create your message for the customer here
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$custom_price = 10; // This will be your custome price
$target_product_id = 944;
foreach ( $cart_object->cart_contents as $value ) {
if ( $value['product_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
/*
// If your target product is a variation
if ( $value['variation_id'] == $target_product_id ) {
$value['data']->price = $custom_price;
}
*/
}
}
}
}
}
add_action( 'woocommerce_single_product_summary', 'sv_purchase_disabled_message', 31 );
Here is the way to make it work in woocommerce 3+ too:
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_price', 10, 1 );
function conditionally_change_cart_items_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Set Here your targeted product ID
$targeted_product_id = 944;
// Set Here your custom price (1st purshase)
$custom_price = 10; // First purshase for product ID 944
// Detecting if customer has already bought The targeted product (944)
if( is_user_logged_in() ){
$customer = wp_get_current_user();
$customer_id = $customer->ID; // customer ID
$customer_email = $customer->email; // customer email
if( wc_customer_bought_product( $customer_email, $customer_id, $targeted_product_id) )
$custom_price = 0; // Set to 0 for other purchases (product ID 944)
}
foreach ( $cart_object->get_cart() as $cart_item ) {
// When targeted product is in cart we change the price
if ( $cart_item['product_id'] == $targeted_product_id ) {
// Woocommerce 3+ compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) )
$cart_item['data']->price = $custom_price;
else
$cart_item['data']->set_price( $custom_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 even in WooCommerce 3+

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 );

Determine language in functions.php [wpml]

I have function in functions.php , which automatically adds woocommerce product by ID to cart when website is visited.
The website is bilingual and the function can't determine translated product ID.
So, I want to know if is possible to add wpml function in functions.php, which determines first language of front end, then executes function, something like this:
<?php if(wpml_getLanguage()=='en'); ?>
---do function for product 22---
<?php elseif(wpml_getLanguage()=='it'); ?>
---do function for product 45--
<?php endif; ?>
My code:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 22;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
You can easily get this by using the native WPML variable ICL_LANGUAGE_CODE.
You can find more information about this topic on the following page:
https://wpml.org/documentation/support/wpml-coding-api/
This can be dropped into functions.php
add_action( 'init', 'add_product_on_language' );
function add_product_on_language(){
if ( ! is_admin() ) {
if( ICL_LANGUAGE_CODE == 'en' ){
$product_id = 22;
} elseif ( ICL_LANGUAGE_CODE == 'it' ) {
$product_id = 45;
}
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}

Categories