I need to apply a previously created coupon in woocommerce cart based on total spent in shop by logged in users. Example, If user already spent $300 or more in previous orders, in the next order, automatically apply "xxx" coupon.
based on "Apply automatically a coupon based on specific cart items count in Woocommerce" answer thread, that is what I have so far:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_cart_items_count', 25, 1 );
function auto_add_coupon_based_on_cart_items_count( $user_id, $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Setting and initialising variables
$coupon = 'descuentolealtad'; // <=== Coupon code
$matched = false;
$customer = new WC_Customer( $user_id );
if( $customer->get_total_spent >= 60 ){
$matched = true; // Set to true
}
// If conditions are matched add coupon is not applied
if( $matched && ! $cart->has_discount( $coupon )){
// Apply the coupon code
$cart->add_discount( $coupon );
// Optionally display a message
wc_add_notice( __('Descuento de Lealtad aplicado'), 'notice');
}
// If conditions are not matched and coupon has been appied
elseif( ! $matched && $cart->has_discount( $coupon )){
// Remove the coupon code
$cart->remove_coupon( $coupon );
// Optionally display a message
//wc_add_notice( __('Descuento de Lealtad removido'), 'error');
}
}
I'm trying to use the dedicated get_total_spent() function from woocommerce but is giving me a blank screen.
Any help is appreciated.
Edit
That is my working code very different as I am using a negative fee:
add_action('woocommerce_cart_calculate_fees' , 'discount_based_on_customer_orders', 10, 1);
function discount_based_on_customer_orders( $cart_object ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Getting "completed" customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
// Orders count
$customer_orders_count = count($customer_orders);
// The cart total
$cart_total = WC()->cart->get_total(); // or WC()->cart->get_total_ex_tax()
// First customer order discount
if( empty($customer_orders) || $customer_orders_count == 0 ){
$discount_text = __('Loyalty Discount', 'woocommerce');
$discount = -7;
}
}
Updated - There is many mistakes in your code like:
For this hook there is only one variable argument: $cart… and not $user_id and $cart
Since Woocommerce 3, use the method get_total_spent() and not the property get_total_spent.
You should first check that user is logged in too.
Use the following revisited code instead:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_total_spent', 10, 1 );
function auto_add_coupon_based_on_total_spent( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Setting and initialising variables
$coupon = 'summer'; // <=== Coupon code
$spent_amount = 60;
$customer = new WC_Customer(get_current_user_id());
// If conditions are matched add coupon is not applied
if( $customer->get_total_spent() >= $spent_amount && ! $cart->has_discount( $coupon )){
// Apply the coupon code
$cart->add_discount( $coupon );
// Optionally display a message
wc_add_notice( __('Descuento de Lealtad aplicado'), 'notice');
}
// If conditions are not matched and coupon has been appied
elseif($customer->get_total_spent() < $spent_amount && $cart->has_discount( $coupon )){
// Remove the coupon code
$cart->remove_coupon( $coupon );
}
}
Code goes in function.php file of your active child theme (or active theme). It should better works.
Related
I have scoured the net and many pages here on stackoverflow. I’m trying to set up a WooCommerce abandoned cart flow where an auto generated coupon in WooCommerce can be added to the cart. I have butchered various code that I’ve found. I have it pretty rough but kinda working. I’m not that familiar with PHP so struggling to get this to behave correctly.
I have the coupon auto generating in WooCommerce admin when a product is added to the cart, its also being applied on the cart page. However every time the page is refreshed more coupons are being generated and added to the cart. Also coupons are generated every time a product is added to the cart.
Is there anyway to limit the coupon so that it is only generated and applied once?
I was planning to direct to the WooCommerce shopping cart from a recreated abandoned cart flow in Klaviyo, where all products from a customers abandoned cart will be added. I was planning to append the URL with something like https://example.com/cart?coupon-code=mycoupon
Would it at all be possible to trigger the coupon creation from the URL variable (eg/ mycoupon) ?
Please let me know if this is even possible? Before I waste another day of my life on this project...lol
Heres my code so far.
function coupon_exists($coupon_code) {
global $wpdb;
$sql = $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_name = '%s'", $coupon_code );
$coupon_codes = $wpdb->get_results($sql);
if (count($coupon_codes)> 0) {
return true;
}
else {
return false;
}
}
// Utility function that generate a non existing coupon code (as each coupon code has to be unique)
function random_coupon_code() {
global $wpdb;
// Get an array of all existing coupon codes
$coupon_codes_check = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon'");
for ( $i = 0; $i < 1; $i++ ) {
$generated_code = strtolower( wp_generate_password( 15, false ) );
// Check if the generated code doesn't exist yet
if( in_array( $generated_code, $coupon_codes_check ) ) {
$i--; // continue the loop and generate a new code
} else {
break; // stop the loop: The generated coupon code doesn't exist already
}
}
return $generated_code;
}
function generate_random_coupon($coupon_generated) {
// Set some coupon data by default
$date_expires = date('Y-m-d', strtotime('+1 days'));
$discount_type = 'fixed_cart'; // 'store_credit' doesn't exist
$coupon_amount = '10';
$coupon = new WC_Coupon();
// Generate a non existing coupon code name
$coupon_code = random_coupon_code();
$coupon->set_code($coupon_generated);
//the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_discount_type($discount_type);
//the discount amount, defaults to zero
$coupon->set_amount($coupon_amount );
$coupon->set_date_expires( $date_expires );
//save the coupon
$coupon->save();
return $coupon_generated;
}
function hwn_add_programmatically_created_coupon_to_basket( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = random_coupon_code();
if (!coupon_exists($coupon_code)) {
generate_random_coupon($coupon_code);
}
$applied_coupons = $cart->get_applied_coupons();
if( ! in_array($coupon_code, $applied_coupons)){
$cart->add_discount( $coupon_code );
wc_print_notices();
}
elseif( in_array($coupon_code, $applied_coupons)){
$cart->remove_coupon( $coupon_code );
}
}
add_action('woocommerce_before_calculate_totals', 'hwn_add_programmatically_created_coupon_to_basket');
https://i.imgur.com/hzGfDkz.png
https://i.imgur.com/2yIlz1a.png
https://i.imgur.com/hfligL9.png
You can get a coupon code from the URL using the GET method. try the below code. You remove the function random_coupon_code because now you generate coupon code based on URL.
function coupon_exists( $coupon_code ) {
global $wpdb;
$sql = $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_name = '%s'", $coupon_code );
$coupon_codes = $wpdb->get_results($sql);
if ( count( $coupon_codes ) > 0 ) {
return true;
} else {
return false;
}
}
function generate_coupon($coupon_generated) {
// Set some coupon data by default
$date_expires = date('Y-m-d', strtotime('+1 days'));
$discount_type = 'fixed_cart'; // 'store_credit' doesn't exist
$coupon_amount = '10';
$coupon = new WC_Coupon();
$coupon->set_code($coupon_generated);
//the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_discount_type($discount_type);
//the discount amount, defaults to zero
$coupon->set_amount($coupon_amount );
$coupon->set_date_expires( $date_expires );
//save the coupon
$coupon->save();
return $coupon_generated;
}
function hwn_add_programmatically_created_coupon_to_basket( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = ( isset( $_GET['coupon-code'] ) && $_GET['coupon-code'] != '' ) ? $_GET['coupon-code'] : '' ;
if( $coupon_code == '' ){
return;
}
$applied_coupons = $cart->get_applied_coupons();
if( empty( $applied_coupons ) || ! in_array( $coupon_code, $applied_coupons ) ){
if ( !coupon_exists( $coupon_code ) ) {
generate_coupon( $coupon_code );
}
$cart->add_discount( $coupon_code );
}
}
add_action('woocommerce_before_calculate_totals', 'hwn_add_programmatically_created_coupon_to_basket');
Tested and works
I would like to apply a coupon automatically based on customer total spent amount. This coupon needs to be applied only one time by customer.
This is what I've tried so far but I'm getting a blank screen:
add_action( 'woocommerce_before_calculate_totals', 'loyalty_order_discount', 10, 1 );
function loyalty_order_discount( $order_id ) {
global $woocommerce;
$coupon = 'loyaltydiscount';
$customer = new WC_Customer(get_current_user_id());
$total_spent = 30;
$order = wc_get_order( $order_id );
foreach( $order->get_used_coupons( $customer ) as $coupon_name ){
// Retrieving the coupon ID
$coupon_post_obj = get_page_by_title($coupon_name, OBJECT, 'shop_coupon');
$coupon_id = $coupon_post_obj->ID;
$coupons_obj = new WC_Coupon($coupon_id);
if( $coupons_obj == $coupon && $customer->get_total_spent() < $total_spent ){
$woocommerce->cart->remove_coupon( $coupon );
}
elseif ( ! $coupons_obj == $coupon && $customer->get_total_spent() >= $total_spent){
$woocommerce->cart->add_discount( $coupon );
}
}
}
Any help is appreciated.
First you need to set, for your coupon, the "Usage limit per user" option to 1 (and save) like:
Now the following revisited code will auto apply a specific coupon only once when the customer total spent has reached a defined amount:
add_action( 'woocommerce_before_calculate_totals', 'enable_customer_loyalty_discount', 10, 1 );
function enable_customer_loyalty_discount( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
//Your settings below
$coupon_code = 'loyaltydiscount';
$coupon_code = 'summer';
$total_spent = 30;
if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) ) {
$user_id = get_current_user_id(); // User ID
// Get the WC_Customer instance Object
$customer = New WC_Customer( $user_id );
$email = $customer->get_billing_email(); // Billing email
// If the user total spent has not reached the define amount, we exit
if( $customer->get_total_spent() < $total_spent ) {
return;
}
// Get the WC_Coupon instance Object
$coupon = New WC_Coupon( $coupon_code );
// If the coupon has already been used by the customer, we exit
if( array_intersect( array($user_id, $email), $coupon->get_used_by() ) {
return;
}
$cart->apply_coupon( $coupon_code );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I wanted to apply a coupon code to cart if cart have minimum 2 items. if not have then the coupon not will apply and show alter message and if have apply then will show a success message here is my code I have tried not working like I want
add_action( 'woocommerce_before_calculate_totals','conditionally_auto_add_coupon', 30, 1 );
function conditionally_auto_add_coupon( $cart ) {
if ( is_admin() && !defined('DOING_AJAX') ) return; // Exit
// HERE set the coupon code (in lowercase)
$coupon_code = 'mycode';
$total_item = 0;
if (WC()->cart->has_discount('mycode')) {
foreach( $cart->get_cart() as $cart_item ){
$total_item++;
}
if($total_item < 2){
$cart->remove_coupon( $coupon_code );
wc_add_notice( __('you have only 1 item in cart'), 'alert');
}
else{
$cart->add_discount( $coupon_code );
wc_add_notice( __('coupon added'), 'notice');
}
}
}
Any help is welcome.
Try the following:
add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_conditionally', 10, 1 );
function auto_apply_coupon_conditionally( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = 'summer'; // HERE set the coupon code (in lowercase)
$applied = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false;
$item_count = sizeof( $cart->get_cart() );
$total_item = 0;
// Remove coupon
if ( $item_count < 2 && $applied ) {
$cart->remove_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __('You have only 1 item in cart'), 'error');
}
// Add coupon
elseif ( $item_count >= 2 && ! $applied ) {
$cart->apply_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __('A coupon has been added'), 'notice' );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works
Please use "Smart Coupon For Woocommerce" plugin implementing the auto coupon functionality,
Please refer this code in svn repo.
I am trying to automatically trigger a coupon to be applied in the cart specifically for when there are 4 items in the cart.
The coupon is pre-created in the Woocommerce back-end of the site "tasterbox"
I am using an amended version from this answer code:
Add WooCommerce coupon code automatically based on product categories
Here is my code version:
add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_coupons', 10, 1 );
function wc_auto_add_coupons( $cart_object ) {
// Coupon code
$coupon = 'tasterbox';
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialising variables
$is_match = false;
$taster_item_count = 4;
// Iterating through each cart item
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If cart items match 4
if( $cart->cart_contents_count == $taster_item_count ){
$is_match = true; // Set to true
break; // stop the loop
}
}
// If conditions are matched add the coupon discount
if( $is_match && ! $cart_object->has_discount( $coupon )){
// Apply the coupon code
$cart_object->add_discount( $coupon );
// Optionally display a message
wc_add_notice( __('TASTER BOX ADDED'), 'notice');
}
// If conditions are not matched and coupon has been appied
elseif( ! $has_category && $cart_object->has_discount( $coupon )){
// Remove the coupon code
$cart_object->remove_coupon( $coupon );
// Optionally display a message
wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'alert');
}
}
However I can not get it to auto apply the coupon when there are 4 items in the cart. It seems like something simple to do, but I'm stuck.
Any help appreciated.
There is some little mistakes and errors in your code. Try the following instead:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_cart_items_count', 25, 1 );
function auto_add_coupon_based_on_cart_items_count( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Setting and initialising variables
$coupon = 'tasterbox'; // <=== Coupon code
$item_count = 4; // <=== <=== Number of items
$matched = false;
if( $cart->cart_contents_count >= $item_count ){
$matched = true; // Set to true
}
// If conditions are matched add coupon is not applied
if( $matched && ! $cart->has_discount( $coupon )){
// Apply the coupon code
$cart->add_discount( $coupon );
// Optionally display a message
wc_add_notice( __('TASTER BOX ADDED'), 'notice');
}
// If conditions are not matched and coupon has been appied
elseif( ! $matched && $cart->has_discount( $coupon )){
// Remove the coupon code
$cart->remove_coupon( $coupon );
// Optionally display a message
wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'error');
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
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+