Can't change product price with woocommerce_after_calculate_totals - php

I want to check some condition and if is true, I want to update the price of all products to 10$.
Everything is working well with this function:
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(true) { // some condition
foreach ( $cart_object->get_cart() as $key => $val ) {
$current_product = $val['data'];
$current_product->set_price( 10 );
}
}
}
But when the user uses a coupon code the above function stops working, the price doesn't change.
Why?
Thank you.

You can raise or lower the priority. Setting it to 999 would put it as the last thing to run.
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_cart_items_price', 999, 1 );
function conditionally_change_cart_items_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if(true) { // some condition
foreach ( $cart_object->get_cart() as $key => $val ) {
$current_product = $val['data'];
$current_product->set_price( 10 );
}
}
}

Related

Disabling payment methods based on custom shipping methods in WooCommerce

In WooCommerce shop I have 2 delivery method based on Parcel locker. The first is payable in advance, while the second is cash on delivery.
The idea is:
easypack_parcel_machines -> only Pay in advance
easypack_parcel_machines_cod -> only Cash on delivery
My code below. After applying in both cases, I only have Pay in advance. What's wrong?
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' );
function gateway_disable_shipping_meth( $available_gateways ) {
if ( ! is_admin() ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ( isset( $available_gateways['bacs'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) {
unset( $available_gateways['cod'] );
}
elseif ( isset( $available_gateways['cod'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines_cod' ) ) {
unset( $available_gateways['bacs'] );
}
}
return $available_gateways;
}
As both shipping methods start with the same slug, you should simply need to invert them in your if / elseif statement as follows (also there are some other mistake):
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' );
function gateway_disable_shipping_meth( $available_gateways ) {
if ( ! is_admin() ) {
$chosen_shipping = WC()->session->get( 'chosen_shipping_methods' )[0];
if ( isset( $available_gateways['bacs'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines_cod' ) ) {
unset( $available_gateways['bacs'] );
}
elseif ( isset( $available_gateways['cod'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) {
unset( $available_gateways['cod'] );
}
}
return $available_gateways;
}
or also this way too:
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' );
function gateway_disable_shipping_meth( $available_gateways ) {
if ( ! is_admin() ) {
$chosen_shipping = WC()->session->get( 'chosen_shipping_methods' )[0];
if ( 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) {
if ( false !== strpos( $chosen_shipping, 'cod' ) && isset( $available_gateways['bacs'] ) ) {
unset( $available_gateways['bacs'] );
} elseif ( isset( $available_gateways['cod'] ) ) {
unset( $available_gateways['cod'] );
}
}
}
return $available_gateways;
}
It should work.

Keep in cart only last added item from specific product category in WooCommerce

I have a situation where user cannot add more than 1 product to cart from specific category. I tried using woocommerce_add_to_cart_validation filter hook.
This code works for all items and keep in cart last added item:
// before add to cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );
function woo_custom_add_to_cart_before( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
// Do nothing with the data and return
return true;
}
This code doesn't work:
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );
function woo_custom_add_to_cart_before( $cart_item_data ) {
if( is_product_category( 'test' ) ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
// Do nothing with the data and return
return true;
}
}
Any help please?
Try this.
add_action( 'woocommerce_before_calculate_totals', 'only_allow_one_item_from_specific_category', 10, 1 );
function only_allow_one_item_from_specific_category( $cart ){
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
if( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
$cart->remove_cart_item( $cart_item['product_id'] );
}
}
}
function custom_maybe_empty_cart( $valid, $product_id, $quantity ) {
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
if( ! empty ( WC()->cart->get_cart() ) && $valid ){
WC()->cart->empty_cart();
wc_add_notice( 'Only allowed 1 item in cart.', 'error' );
}
}
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'custom_maybe_empty_cart', 10, 3 );
This code worked for me pls. Thank you so much for helping everyone.

Allow customer to set the product price and add to cart with certain validations in WooCommerce

I'm working on a giftcard product whereof I need the customer to be able to set the price as long as it is 100 or more. Problem is, I'm not sure how to create the value check.
The customer should then be able to add to cart as normal and to checkout as usual.
I've included a remove_action for the product price (which for some reason does not work) if the product is assigned to the giftcard category.
The field input has been created and the data should be carried over to the cart and checkout and into the order -- but it does not work for some reason.
The next step is to set the product price into whatever the customer submits as the giftcard value (as long as it is 100 or more) and to display that as the product price on cart and checkout.
If anyone can review and help me out, that would be awesome.
add_action( 'woocommerce_before_add_to_cart_form', 'giftcard_price_field' );
function giftcard_price_field() {
global $product;
if( has_term('giftcard', 'product_cat', $product->get_id() ) ) {
// if the product is assigned to the giftcard category, remove the product price
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
// add a new input field for the price, allowing the customer to set the price
echo '<div class="giftcard-product-price">
<label for="giftcard-product-price">Giftcard value: </label>
<input type="text" id="giftcard-product-price" name="giftcard-product-price" placeholder="Giftcard value" maxlength="1000">
</div>';
}
}
add_filter( 'woocommerce_add_cart_item_data', 'giftcard_price_field_cart_data', 10, 3 );
function giftcard_price_field_cart_data( $cart_item_data, $product_id, $variation_id ) {
if( ! empty ( $_POST[ 'giftcard-product-price' ] ) ) {
// need to check that the value is NOT below 100 and if so, create a wc_notice warning
$cart_item_data['giftcard-product-price'] = sanitize_text_field( $_POST['giftcard-product-price']);
}
return $cart_item_data;
}
add_filter( 'woocommerce_get_item_data', 'giftcard_price_field_display_data', 10, 2 );
function giftcard_price_field_display_data( $item_data, $cart_item ) {
if( ! empty ( $cart_item[ 'giftcard-product-price' ] ) ) {
$item_data[] = array (
'key' => 'Giftcard value',
'value' => $cart_item['giftcard-product-price'],
'display' => '',
);
}
return $item_data;
}
add_action( 'woocommerce_checkout_create_order_line_item', 'giftcard_price_field_order_data', 10, 4 );
function giftcard_price_field_order_data( $item, $cart_item_key, $values, $order ) {
if( ! empty ( $values[ 'giftcard-product-price' ] ) ) {
$item->add_meta_data( 'Giftcard value', $values['giftcard-product-price'] );
}
}
Add a new field 'giftcard_product_price' on single product page if has_term()
Removes the original product price on the single product page
Various validations have been added and are possible
The price of the product (giftcard) is adjusted to the price entered by the customer
function giftcard_price_field() {
global $product;
// Instanceof
if ( $product instanceof WC_Product ) {
// Set category(ies)
$cats = array ( 'giftcard' );
// True
if ( has_term( $cats, 'product_cat', $product->get_id() ) ) {
// add a new input field for the price, allowing the customer to set the price
echo '<div class="giftcard-product-price">
<label for="giftcard-product-price">Giftcard value: </label>
<input type="text" id="giftcard_product_price" name="giftcard_product_price" placeholder="Giftcard value" maxlength="1000">
</div>';
}
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'giftcard_price_field', 10, 0 );
// Remove price
function action_woocommerce_single_product_summary() {
global $product;
// Instanceof
if ( $product instanceof WC_Product ) {
// Set category(ies)
$cats = array ( 'giftcard' );
// True
if ( has_term( $cats, 'product_cat', $product->get_id() ) ) {
remove_action('woocommerce_single_product_summary','woocommerce_template_single_price', 10 );
}
}
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 5 );
// Validate
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Isset
if ( isset ( $_POST['giftcard_product_price'] ) ) {
$giftcard_product_price = $_POST['giftcard_product_price'];
// Error = empty, not numeric or less than 100
if ( empty ( $giftcard_product_price ) ) {
wc_add_notice( __( 'Field is empty', 'woocommerce' ), 'error' );
$passed = false;
} elseif ( ! is_numeric ( $giftcard_product_price ) ) {
wc_add_notice( __( 'NOT a number or a numeric string', 'woocommerce' ), 'error' );
$passed = false;
} elseif ( $giftcard_product_price < 100 ) {
wc_add_notice( __( 'Less than 100', 'woocommerce' ), 'error' );
$passed = false;
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
function filter_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
if ( isset ( $_POST['giftcard_product_price'] ) ) {
$cart_item_data['giftcard_product_price'] = sanitize_text_field( $_POST['giftcard_product_price'] );
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data', 10, 3 );
// Set price
function action_woocommerce_before_calculate_totals( $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 ) {
if ( isset ( $cart_item['giftcard_product_price'] ) ) {
$cart_item['data']->set_price( $cart_item['giftcard_product_price'] );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );

Automatic discount for paying customers in WooCommerce

I want to apply a discount coupon automatically to everyone who has made at least one purchase on my website. This is the code that I tried but I get a fatal error on the page ...
function has_bought( $customer_email ){
$orders = get_posts(array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array('wc-completed'),
) );
$email_array = array();
foreach($orders as $order) {
$order_obj = wc_get_order($order->ID);
$order_obj_data = $order_obj->get_data();
array_push($email_array, $order_obj_data['billing']['email']);
}
if (in_array($customer_email, $email_array)) {
return true;
} else {
return false;
}
}
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code = '10fidelity'; // coupon code
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
if ( has bought() {
$woocommerce->cart->add_discount( $coupon_code );
$woocommerce->show_messages();
}
}
Your actual code is heavy and outdated… Instead try the following much more lighter and efficient way, that use the WC_Customer is_paying_customer property:
add_action( 'woocommerce_before_calculate_totals', 'enable_customer_fidelity_discount', 10, 1 );
function enable_customer_fidelity_discount( $cart ) {
if ( ! ( is_cart() || is_checkout() ) )
return;
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// The discount coupon code below
$coupon_code = '10fidelity';
if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) && WC()->customer->get_is_paying_customer() ) {
$cart->apply_coupon( $coupon_code );
} elseif( in_array( $coupon_code, $cart->get_applied_coupons() ) && ! WC()->customer->get_is_paying_customer() ) {
$cart->remove_coupon( $coupon_code );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works
Or using this improved and light function that checks if customer has already made an order:
function has_bought( $user_id = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 ? get_current_user_id() : $user_id;
$paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
$results = $wpdb->get_col( "
SELECT p.ID FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' )
AND p.post_type LIKE 'shop_order'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
" );
// Count number of orders and return a boolean value depending if higher than 0
return count( $results ) > 0 ? true : false;
}
add_action( 'woocommerce_before_calculate_totals', 'enable_customer_fidelity_discount', 10, 1 );
function enable_customer_fidelity_discount( $cart ) {
if ( ! ( is_cart() || is_checkout() ) )
return;
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// The discount coupon code below
$coupon_code = 'summer';
if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) && has_bought() ) {
$cart->apply_coupon( $coupon_code );
} elseif( in_array( $coupon_code, $cart->get_applied_coupons() ) && ! has_bought() ) {
$cart->remove_coupon( $coupon_code );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related:
Checking if customer has already bought something in WooCommerce
Auto apply coupon only one time per user based on total spent in WooCommerce

Buy one get one in woocommerce with out coupon code

I want implement functionality on my site when user buy a x product then user will get a y product as free.
In my site i have variable products.If customer buy 1kg pack of X product then customer want to get Free 30ml of Y product.
I added below code in my function.php but its working the problem is when refreshing the page gift product count is increasing.
my updated code.
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
function bbloomer_apply_matched_coupons() {
global $woocommerce;
$cat_in_cart = false;
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
// this is your product ID
$autocoupon = array( 123411 );
if( in_array( $values['variation_id'], $autocoupon ) ) {
$cat_in_cart = true;
break;
}
}
if ( $cat_in_cart ) {
$product_id = 2044;
$quantity = 1;
$variation_id = 2046;
$variation = array(
'pa_size' => '30ml'
);
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
}
}
Add this to start of 'functions.php'.
ob_start();
session_start();
Then add this code.
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
function bbloomer_apply_matched_coupons() {
if(!$_SESSION['GiftAdded']) {
global $woocommerce;
$cat_in_cart = false;
$coupon_in_cart = false;
$autocoupon = array( 123411 ); // variation ids of products that offers gifts
$freecoupon = array( 2046 ); // variation ids of products that are gift coupons
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
if( in_array( $values['variation_id'], $autocoupon ) ) {
$cat_in_cart = true;
}
if( in_array( $values['variation_id'], $freecoupon) ) {
$coupon_in_cart = true;
}
}
if ( $cat_in_cart && !$coupon_in_cart ) {
$product_id = 2044;
$quantity = 1;
$variation_id = 2046;
$variation = array( 'pa_size' => '30ml' );
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
$_SESSION['GiftAdded']=true;
}
}
}
The $_SESSION['GiftAdded'] will prevent the gift product added again when its deleted manually.
There is an other alternative based on quantity using another hook… It handles when quantities are changed or products removed from cart and set the price of the free product to zero:
add_action( 'woocommerce_before_calculate_totals', 'add_free_product_to_cart', 20, 1 );
function add_free_product_to_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$products_ids = array( 123411 ); // Products IDs to check
$free_var_id = 2046; // free product (variation ID)
$free_prod_id = 2044; // free product (product ID)
$free_attr = array( 'pa_size' => 'medium' ); // Free product attribute
$free_price = 0;
$targeted = $free = array('qty' => 0 ); // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( in_array( $cart_item['data']->get_id(), $products_ids ) ) {
$targeted['qty'] += $cart_item['quantity'];
} elseif ( $cart_item['data']->get_id() == $free_var_id ) {
$cart_item['data']->set_price($free_price);
$free['qty'] += $cart_item['quantity'];
$free['key'] = $cart_item_key;
}
}
// We exit (No changes are needed)
if( $targeted['qty'] == $free['qty'] )
return;
if( $targeted['qty'] > 0 && $free['qty'] == 0 )
{
// Add the free product
$cart->add_to_cart( $free_prod_id, $targeted['qty'], $free_var_id, $free_attr );
}
elseif( $targeted['qty'] > 0 && $free['qty'] > 0 && $targeted['qty'] != $free['qty'] )
{
// Adjust free product quantity
$cart->set_quantity( $free['key'], $targeted['qty'] );
}
elseif( $targeted['qty'] == 0 && $free['qty'] > 0)
{
// Remove free product
$cart->remove_cart_item( $free['key'] );
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Categories