Limit Sale Products

Limits the maximum number of sale products that can be purchased per order.

PHP
/**
 * Snippet Name:     Limit Sale Products
 * Snippet Author:   coding-bunny.com
 * Description:      Limits the maximum number of sale products that can be purchased per order.
 */

add_action( 'woocommerce_before_calculate_totals', 'cblsp_limit_sale_products_qty_in_cart', 10, 1 );
add_action( 'woocommerce_after_add_to_cart_button', 'cblsp_show_sale_limit_message_below_add_to_cart' );
add_action( 'wp_footer', 'cblsp_ajax_update_sale_limit_message_script' );

function cblsp_limit_sale_products_qty_in_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    /// SET QUANTITY HERE ///
    $max_qty        = 2;
    ////////////////////////
    
    $total_sale_qty = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( isset( $cart_item['data'] ) && is_a( $cart_item['data'], 'WC_Product' ) && $cart_item['data']->is_on_sale() ) {
            $total_sale_qty += intval( $cart_item['quantity'] );
        }
    }

    if ( $total_sale_qty > $max_qty ) {
        $qty_to_remove = $total_sale_qty - $max_qty;

        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( isset( $cart_item['data'] ) && is_a( $cart_item['data'], 'WC_Product' ) && $cart_item['data']->is_on_sale() && $qty_to_remove > 0 ) {
                $current_qty = intval( $cart_item['quantity'] );
                $remove_qty  = min( $qty_to_remove, $current_qty );
                $new_qty     = $current_qty - $remove_qty;
                $cart->set_quantity( $cart_item_key, $new_qty );
                $qty_to_remove -= $remove_qty;
            }
            if ( $qty_to_remove <= 0 ) {
                break;
            }
        }

        wc_add_notice(
            sprintf(
                'You can purchase a maximum of %d sale items per order.',
                intval( $max_qty )
            ),
            'notice'
        );
    }
}

function cblsp_show_sale_limit_message_below_add_to_cart() {
    echo '<div id="cblsp-sale-limit-message" style="margin-top:10px;"></div>';
}

add_action( 'wp_ajax_cblsp_get_sale_limit_message', 'cblsp_get_sale_limit_message_ajax' );
add_action( 'wp_ajax_nopriv_cblsp_get_sale_limit_message', 'cblsp_get_sale_limit_message_ajax' );

function cblsp_get_sale_limit_message_ajax() {
    $max_qty        = 2;
    $total_sale_qty = 0;
    $cart           = WC()->cart;

    if ( ! $cart ) {
        wp_send_json_success( array( 'message' => '' ) );
    }

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( isset( $cart_item['data'] ) && is_a( $cart_item['data'], 'WC_Product' ) && $cart_item['data']->is_on_sale() ) {
            $total_sale_qty += intval( $cart_item['quantity'] );
        }
    }

    $message = '';
    if ( $total_sale_qty >= $max_qty ) {
        $message = '<span style="color:#b32d2e; font-size:14px;">' .
            sprintf(
                'You can purchase a maximum of %d sale items per order.',
                intval( $max_qty )
            ) .
            '</span>';
    }

    wp_send_json_success( array( 'message' => $message ) );
}

function cblsp_ajax_update_sale_limit_message_script() {
    if ( ! is_product() ) {
        return;
    }
    ?>
    <script>
    (function($) {
        function updateSaleLimitMessage() {
            $.ajax({
                url: '<?php echo esc_url( admin_url( "admin-ajax.php" ) ); ?>',
                type: 'POST',
                data: {
                    action: 'cblsp_get_sale_limit_message'
                },
                success: function(response) {
                    if(response.success && typeof response.data.message !== 'undefined') {
                        $('#cblsp-sale-limit-message').html(response.data.message);
                    }
                }
            });
        }

        $(document).ready(function() {
            updateSaleLimitMessage();
            $('body').on('added_to_cart', updateSaleLimitMessage);
        });
    })(jQuery);
    </script>
    <?php
}

How To Implement This Solution?

Leave a Reply