Home / eCommerce / Disallow Store Credit When There Is an Active Coupon in the Cart
Duplicate Snippet

Embed Snippet on Your Site

Disallow Store Credit When There Is an Active Coupon in the Cart

- When you apply coupon first, once the cart refreshes, the Store Credit field will be hidden
- When you apply store credit first, and then apply coupon, the store credit will be kicked out
- If you try reapply the store credit, a notification will appear "Some of the items in your cart are not allowed to be paid via store credit.

"

Code Preview
php
<?php
/**
 * Hide store credit field when a regular coupon is applied.
 * Also removes any already-applied store credit when a coupon is added.
 */
// PHP: Hide store credit on AJAX checkout refresh when coupon is active
add_filter( 'acfw_is_allow_store_credits', function( $is_allowed ) {
    if ( ! $is_allowed || ! WC()->cart ) {
        return $is_allowed;
    }
    $sc_code = strtolower( (string) apply_filters( 'acfw_store_credit_coupon_code', 'store credit' ) );
    foreach ( WC()->cart->get_applied_coupons() as $code ) {
        if ( strtolower( $code ) !== $sc_code ) {
            return false;
        }
    }
    return $is_allowed;
}, 10, 1 );
// PHP: Remove active store credit when a regular coupon is applied
add_action( 'woocommerce_applied_coupon', function( $coupon_code ) {
    $sc_code = strtolower( (string) apply_filters( 'acfw_store_credit_coupon_code', 'store credit' ) );
    if ( strtolower( $coupon_code ) === $sc_code ) {
        return;
    }
    if ( ! WC()->session || ! WC()->cart ) {
        return;
    }
    WC()->session->set( 'acfw_store_credits_discount', null );
    WC()->session->set( 'acfw_store_credits_coupon_discount', null );
    $applied = WC()->cart->get_applied_coupons();
    $updated = array_values( array_filter( $applied, function( $code ) use ( $sc_code ) {
        return strtolower( $code ) !== $sc_code;
    } ) );
    if ( count( $updated ) < count( $applied ) ) {
        WC()->cart->set_applied_coupons( $updated );
        WC()->cart->calculate_totals();
    }
}, 10, 1 );
// JS: Immediately show/hide the field on coupon apply/remove (before AJAX refresh)
add_action( 'wp_footer', function() {
    if ( ! is_checkout() ) {
        return;
    }
    ?>
    <script>
    jQuery( function( $ ) {
        function toggleStoreCreditSection() {
            var hasCoupon = $( '.cart-discount' ).length > 0;
            $( '.acfw-accordion.acfw-store-credits-checkout-ui' ).toggle( ! hasCoupon );
        }
        $( document.body ).on( 'applied_coupon removed_coupon updated_checkout', function() {
            toggleStoreCreditSection();
        });
        toggleStoreCreditSection();
    } );
    </script>
    <?php
} );

Comments

Add a Comment