Search code examples
wordpresswoocommercehook-woocommerce

How to add a step of 100 and inscribe in the quantity of goods? WooCommerce


I have a website. I wrote a code that adds "per 100g" to the product price (in the picture point 2). Here is the code:

add_filter( 'woocommerce_get_price_html', 'wb_change_product_html' );

function wb_change_product_html( $price ) {

    $cat_arr = get_the_terms(get_the_ID(),'product_cat');
    //return $a[0]->name;
    $temp = 0;
    foreach ($cat_arr as $singl_cat) {
        if($singl_cat->name == 'perunit') {
            $temp = 1;
        }
    }
    if ( $temp ) {
        $price_html = '<span class="amount">' . 'per unit \' ' . $price . '</span>';

    } else {
        $price_html = '<span class="amount">' . ' per 100g \ ' . $price . '</span>';
    }
    return $price_html;

}

I need to add an inscription to the "number of items added to the cart" (in the picture point 1). The logic is that if I have a category "per unit", then everything remains by default. But if there is no category, then the inscription "price per X gram" is added to the quantity of goods, where X is the quantity of grams (minimum 100) and take a step of 100 grams.

I don't know how to do this, can anyone suggest?

enter image description here


Solution

  • It's pretty simple (from official docs https://docs.woocommerce.com/document/adjust-the-quantity-input-values/) - add this to your functions.php

    /**
     * Adjust the quantity input values
     */
    add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products
    
    function jk_woocommerce_quantity_input_args( $args, $product ) {
        $cat_arr = get_the_terms(get_the_ID(),'product_cat');
        if( 'perunit' == $cat_arr[0]->name ) {
            if ( is_singular( 'product' ) ) {
                $args['input_value']    = 100;  // Starting value (we only want to affect product pages, not cart)
            }
            $args['max_value']  = 1000;     // Maximum value
            $args['min_value']  = 100;      // Minimum value
            $args['step']       = 100;    // Quantity steps
            return $args;
        }
    }