Adjust input quantities for product variations in Woocommerce

In my WooCommerce store, I encountered an issue with a variable product that has 3 product variations.

Unfortunately, the quantity to sell for each variation needs to be fixed and cannot be adjusted by the customer.

For instance:

We have 2 Red items available at a price of 10,00€ each.
Furthermore, we offer 3 Blue items for 12,00€ each.
Lastly, there are 6 Green items available at 16,00€ per unit.

Therefore, it is crucial that the customer selects either 3 red, 6 blue, or 12 green items when placing an order. They should not be able to purchase any other quantities.

Answer №1

The two functions below require you to first set the parent variable product ID and then, in the first function, assign each variation ID with a corresponding fixed quantity.

To dynamically set the input quantity based on each selected variation, the only way is to use Javascript (JQuery). This is achieved in the second function.

Here is the code:

add_filter( 'woocommerce_available_variation', 'custom_variation_min_max_qty', 10, 3 );
function custom_variation_min_max_qty( $data, $product, $variation ) {
    // Set your variable product ID
    $variable_id = 73;

    if( $product->get_id() == $variable_id ) {
        // Set 1st variation ID
        if( $variation->get_id() == 1015 ){
            $qty = 3; // Set the quantity
        } 
        // Set 2nd variation ID
        elseif( $variation->get_id() == 1014 ){
            $qty = 6; // Set the quantity
        }
        // Set 3rd variation ID
        elseif( $variation->get_id() == 1013 ){
            $qty = 12; // Set the quantity
        }
    }

    if( isset($qty) ) {
        $data['min_qty'] = $qty;
        $data['max_qty'] = $qty;
    }

    return $data;
}

add_action( 'woocommerce_after_single_variation',  'change_variation_input_quantity_script' );
function change_variation_input_quantity_script() {
    global $product;

    // Set your variable product ID
    $variable_id = 73;

    if( $product->get_id() != $variable_id ) return;

    // Output Javascript
    ?>
    <!-- JS Thankyou Script -->
    <script type="text/javascript">
    jQuery(function($) {
        var a = 'div.quantity > input.qty';
        // On load
        setTimeout(function(){
            $(a).val($(a).prop('min'));
        }, 300);

        // On change / select a variation
        $('.variations_form select').on( 'blur', function(){
            if( $('input[name="variation_id"]').val() > 0 )
                $(a).val($(a).prop('min'));
        })

    });
    </script>
    <?php
}

Place this code in the function.php file of your active child theme (or active theme). It has been tested and proven to work.


It is possible to automate the correct variation detection based on specific product attribute values...

In the example given, this can be achieved by targeting the color product attribute value of a variation. In the function, you will need to define the "Color" product attribute taxonomy as pa_color.

Therefore, you would replace the first function with the following:

add_filter( 'woocommerce_available_variation', 'custom_variation_min_max_qty', 10, 3 );
function custom_variation_min_max_qty( $data, $product, $variation ) {
    // Set your variable product ID
    $variable_id = 73;

    if( $product->get_id() == $variable_id ) {
        // Define your product attribute (always start with "pa_" + the slug)
        $taxonomy = 'pa_color';

        foreach($data['attributes'] as $attribute => $value_slug ){
            if( $attribute == 'attribute_' . $taxonomy ) {
                // Set your color slugs below with the correct quantity
                if ( $value_slug == 'red' ) 
                {
                    $qty = 3; // Set the quantity for "Red" color
                    break;
                }
                elseif ( $value_slug == 'blue' )
                {
                    $qty = 6; // Set the quantity for "Blue" color
                    break;
                }
                elseif ( $value_slug == 'green' )
                {
                    $qty = 12; // Set the quantity for "Green" color
                    break;
                }
            }
        }
    }

    if( isset($qty) ) {
        $data['min_qty'] = $qty;
        $data['max_qty'] = $qty;
    }

    return $data;
}

You should keep the second function as it is.

Place this code in the function.php file of your active child theme (or active theme). It has been tested and proven to work.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom PHP data caching service

I am in need of implementing a speedy caching mechanism for a PHP application. The setup involves multiple node servers requesting data from a centralized server via a JSON service. These node servers are required to cache the responses on the file syste ...

Updating a column name in MySQL with join operations

In my database, I have a table called data_table with a primary key defined as d_id and other fields labeled f1 to f25. There is another table named fields_name where field names are stored with values f_id, field_name, and order. My goal is to retrieve a ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

What is the correct way to implement include or require_once within an If else statement in PHP?

I have two files named if.php and index.php. I am trying to use if.php to store the if condition for an if statement. However, it does not seem to be working as expected. Is it possible to achieve this? Thank you. if.php <?php if(Three == 3) { //do ...

reveal the concealed divs within the list elements

html: In my HTML document, I have a unordered list (ul) with each list item (li) constructed like this: <li class="A">list-item <div>1</div> <div class="B">2 <div class="C">3</div> </div> ...

Condition formulation using dynamic dust JS equality

I'm struggling with a seemingly simple task - dynamically changing the @eq condition. The example provided shows a default render, but what I really need is to allow user input to change it to either "Larry" or "Moe". You can view my code on jsfiddle ...

Is it possible to add and delete DIVs simply by clicking on a link?

By utilizing a select dropdown list and appending the HTML code stored in the variable "code" (resembling <div>...</div>) right before the end of the div with ID mydiv using $(code).appendTo('#mydiv');. Within these dynamically added ...

Download a file using PHP and cURL

I recently wrote a PHP function to download some files with the .exe extension using the Curl extension. The download is successful, but when I try to open the file, I encounter a "not compatible" error. To investigate further, I opened the file in Notep ...

Show and store extra custom cart item information in Woocommerce Cart, Checkout, and Orders

I'm struggling to include product in the cart with cart item meta data. Here is my code snippet: $cart_item_data = array(); $cart_item_data['add_size'] = array('PR CODE'=>'1.0'); print_r(WC()->cart->add_to_car ...

Access Denied: XAMPP 403 Error

Currently using the php-mvc-master framework on localhost. After changing the Document Root to the framework directory, I encountered this error: Screenshot of error when accessing localhost with changed Document Root directory View the Error Log here W ...

Align dropdown navigation menu/sorting dropdown in the same position as the button

Exploring the world of dropdown menus in CSS has led me to encounter some challenges. I am striving to ensure that the dropdown boxes appear on the same line as the button that triggers them. Below is the CSS code I have been working with: /* global style ...

Guide on parsing a JSON object in JavaScript

One issue I'm facing is that my controller method returns a string representation of a jsonArray using the jsonArray.toString() function. Below is the corresponding ajax method: function loadPropertyFile(url) { $.ajax({ type: "GET", url: url, ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

Unlock the secrets of creating an interactive chat room effortlessly by harnessing the power of J

In search of implementing a unique chat room using PHP and JavaScript (Jquery) offering group chat as well as private chat functionalities. The challenge lies in finding a way to continuously update the interface seamlessly, while also displaying 'X ...

What is the best way to add a blob to the document object model (

I am a beginner when it comes to working with blobs, and I am looking for some guidance to avoid wasting hours on unsuccessful brute-force attempts. I have been using the PHP code below (sourced from here) to retrieve the base64-encoded image from my data ...

One of the arguments sent to the method `GloudemansShoppingcartCart::search()` in Laravel

Client Side: <form action="update_order/{{$item->id}}" method="post"> <input type="hidden" name="_token" value="{{ csrf_token() }}" /> <input type="number" name="qt ...

Activate a jQuery collapsible feature through an external hyperlink

Can we enable the expansion of a jQuery collapse by clicking on an external link? For instance, let's say we have a link on the home page that leads to another page. When the user clicks on this link from the home page, we want it to redirect to the i ...

Enhancing compatibility between Symfony 2.3 and 1.4 for seamless user experience

Recently, I encountered a situation at work where we have two different websites that share the same user login credentials. One website is built on Symfony 2.3 while the other one relies on version 1.4. My boss has assigned me the task of enabling seamles ...

Is there a way for me to utilize a single set of checkboxes for submitting multiple times in order to generate multiple selections simultaneously?

I'm exploring the idea of using checkboxes that can be dynamically updated and posted to a PHP page multiple times. The goal is to send different sets of selections from the same checkboxes to the PHP page, with each set being treated as data for furt ...

How can I programmatically close the Date/Time Picker in Material UI Library?

Is there a way to programmatically close the Date/Time Picker in Material UI Library? ...