Created
September 20, 2024 13:26
-
-
Save xlplugins/6e05bb699cf7734a75676cd321989d0f to your computer and use it in GitHub Desktop.
Apply coupon even when cart empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function to store the coupon in the session on the homepage | |
function store_coupon_in_session() { | |
if ( ! is_checkout() && class_exists( 'WooCommerce' ) ) { | |
// Replace 'your-coupon-code' with your actual coupon code | |
$coupon_code = 'test'; | |
// Save the coupon code in WooCommerce session | |
WC()->session->set( 'stored_coupon_code', $coupon_code ); | |
// Apply coupon immediately if the cart is initialized | |
if ( ! WC()->cart->has_discount( $coupon_code ) && WC()->cart->get_cart_contents_count() == 0 ) { | |
WC()->cart->add_to_cart( 0 ); // Initialize cart session | |
WC()->cart->apply_coupon( $coupon_code ); | |
WC()->cart->empty_cart(); // Remove the fake item | |
} | |
} | |
} | |
add_action( 'wp', 'store_coupon_in_session', 4 ); | |
// Function to apply the stored coupon when a product is added to the cart | |
function apply_stored_coupon_on_add_to_cart() { | |
if ( class_exists( 'WooCommerce' ) && WC()->session ) { | |
// Retrieve the coupon code from the session | |
$coupon_code = WC()->session->get( 'stored_coupon_code' ); | |
// Check if the coupon code exists and is not already applied | |
if ( $coupon_code && ! WC()->cart->has_discount( $coupon_code ) ) { | |
WC()->cart->apply_coupon( $coupon_code ); | |
} | |
} | |
} | |
add_action( 'wfacp_after_checkout_page_found', 'apply_stored_coupon_on_add_to_cart' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment