Add Checkbox to Apply Coupon at Add to Cart Button

Adds a checkbox near the add-to-cart button on WooCommerce product pages for applying a discount coupon.

PHP
/**
 * Snippet Name:      Add Checkbox to Apply Coupon at Add to Cart Button
 * Snippet Author:    coding-bunny.com
 * Description:       Adds a checkbox near the add-to-cart button on WooCommerce product pages for applying a discount coupon.
 */

/**
 * Display a coupon checkbox below the add-to-cart button
 */
add_action( 'woocommerce_after_add_to_cart_button', 'cb_coupon_checkbox', 10 );
function cb_coupon_checkbox() {
    echo '<p style="display: inline-block; margin-top:20px;">
            <span style="background-color: #2d2d2d; color: white; font-weight: bold; padding: 5px 10px; border-radius: 3px;">
                BLACK FRIDAY
            </span> 
            <label style="color: #2d2d2d;">
                <input type="checkbox" name="cb_apply_coupon" value="1"/> 
                Save 10% by activating the discount code!
            </label>
          </p>';
}

/**
 * Apply the coupon when the checkbox is selected
 *
 * @param string $cart_item_key Cart item key.
 * @param int $product_id Product ID.
 * @param int $quantity Quantity of the product.
 * @param int $variation_id Variation ID.
 * @param array $variation Variation details.
 * @param array $cart_item_data Additional cart item data.
 */
add_action( 'woocommerce_add_to_cart', 'cb_apply_coupon_on_checkbox_check', 10, 6 );
function cb_apply_coupon_on_checkbox_check( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
    if ( isset( $_POST['cb_apply_coupon'] ) && $_POST['cb_apply_coupon'] == 1 ) {
        $coupon_code = 'discount10'; // Replace with your actual coupon code
        
        // Apply the coupon only if it is not already applied
        if ( ! WC()->cart->has_discount( $coupon_code ) ) {
            WC()->cart->apply_coupon( $coupon_code );
        }
    }
}

How To Implement This Solution?

Leave a Reply

Your email address will not be published. Required fields are marked *

My Agile Privacy
This site uses technical and profiling cookies. You can accept, decline or customize cookies by pressing the desired buttons. By closing this policy you will continue without accepting.

Need help?

Choose one of the following options:

Powered by CodingBunny