Home / Admin / WooCommerce Product Settings: Enabling Custom Discount Options with Checkbox and Input Field First set quantity only – No Plugin
Duplicate Snippet

Embed Snippet on Your Site

WooCommerce Product Settings: Enabling Custom Discount Options with Checkbox and Input Field First set quantity only – No Plugin

Post More Detail
Here’s an explanation of the features we are going to add using the code snippet in point form:

Checkbox for applying custom discounts: The code snippet will allow you to add a checkbox to the product settings in WooCommerce. This checkbox will enable you to activate custom discounts for specific products.
Input field for discount amount: Along with the checkbox, we’ll also add an input field where you can enter the discount amount for the selected product. This input field will provide the flexibility to define the discount based on your promotional strategy.
Dynamic discounts for tailored promotions: With the custom discount options enabled, you’ll have the ability to create dynamic discounts for your products. This means you can implement various promotional deals such as “buy one, get one free” or “buy two, get 50% off on the third item.”
Seamless integration using Code Snippets plugin: To incorporate these custom discount features into your WooCommerce store, we’ll be utilizing the Code Snippets plugin. This plugin allows you to easily add and manage code snippets without modifying your theme’s files directly.
Implementation via theme’s functions.php file: The provided code snippet will be added to your theme’s functions.php file. This ensures that the custom discount options are seamlessly integrated into your store’s functionality.
By implementing these features, you can enhance your WooCommerce store by offering tailored discounts to your customers, boosting sales, and providing an exceptional shopping experience.

Code Preview
php
<?php
// Add checkbox and input field to general tab
add_action('woocommerce_product_options_general_product_data', 'add_custom_fields_to_general_tab');
function add_custom_fields_to_general_tab() {
    global $post;
    // Retrieve the current values of the checkbox and input field
    $checked = get_post_meta($post->ID, '_allow_discount', true);
    $required_quantity = get_post_meta($post->ID, '_required_quantity', true);
    // Output the checkbox HTML
    woocommerce_wp_checkbox(array(
        'id' => '_allow_discount',
        'label' => __('Allow Discount'),
        'description' => __('Check this box to allow the "E.g buy 3x, get 1 free first set only" discount on this product.'),
        'value' => $checked,
    ));
    echo '<div class="options_group">';
    // Output the input field HTML
    woocommerce_wp_text_input(array(
        'id' => '_required_quantity',
        'label' => __('Required Quantity for Discount'),
        'description' => __('Enter the number of products required for the discount to apply.'),
        'type' => 'number',
        'custom_attributes' => array(
            'step' => '1',
            'min' => '1',
            'value' => $required_quantity,
        ),
    ));
    echo '</div>';
}
// Save checkbox and input field values when product is saved
add_action('woocommerce_process_product_meta', 'save_custom_fields_values');
function save_custom_fields_values($post_id) {
    $checkbox_value = isset($_POST['_allow_discount']) ? 'yes' : 'no';
    $required_quantity_value = isset($_POST['_required_quantity']) ? intval($_POST['_required_quantity']) : 0;
    update_post_meta($post_id, '_allow_discount', $checkbox_value);
    update_post_meta($post_id, '_required_quantity', $required_quantity_value);
}
// Apply custom discount label to specific products
add_action('woocommerce_cart_calculate_fees', 'apply_custom_discount');
function apply_custom_discount() {
    if (is_admin() && !defined('DOING_AJAX'))
        return;
    // Get the cart instance
    $cart = WC()->cart;
    // Initialize variables
    $discount_amount = 0;
    $applied_discount = false;
    // Loop through cart items
    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $allow_discount = get_post_meta($product_id, '_allow_discount', true);
        $required_quantity = get_post_meta($product_id, '_required_quantity', true);
        $quantity_in_cart = $cart_item['quantity'];
        if (!$applied_discount && $allow_discount === 'yes' && $quantity_in_cart >= ($required_quantity + 1)) {
            // Calculate the number of free products
            $free_product_count = 1;
            // Calculate discount amount for the first X products
            $discount_amount = $cart_item['data']->get_price() * $free_product_count;
            // Apply discount with custom label
            $discount_label = __('Buy x Get +1pc Discount', 'your-text-domain'); // Replace 'your-text-domain' with your theme or plugin text domain
            $cart->add_fee($discount_label, -$discount_amount);
            $applied_discount = true;
            break;
        }
    }
}
// Display notice on the front end of the product
add_action('woocommerce_after_add_to_cart_button', 'display_product_discount_notice');
function display_product_discount_notice() {
    global $product;
    // Retrieve the product ID
    $product_id = $product->get_id();
    // Retrieve the values of the checkbox and input field
    $allow_discount = get_post_meta($product_id, '_allow_discount', true);
    $required_quantity = get_post_meta($product_id, '_required_quantity', true);
    if ($allow_discount === 'yes' && $required_quantity > 0) {
        $discount_notice = sprintf(
            __('Buy %s+1 Get 1pc Free Discount', 'your-text-domain'), // Replace 'your-text-domain' with your theme or plugin text domain
            $required_quantity,
            $required_quantity
        );
        // Output the discount notice with updated styles
        echo '<div style="width: 100%; margin-top: 10px; box-sizing: border-box; display: flex; justify-content: center;">
                <div style="background-color: #4CAF50; color: white; padding: 10px; font-size: 16px; border-radius: 5px; text-align: center;">' . esc_html($discount_notice) . '</div>
              </div>';
    }
}

Comments

Add a Comment