Search code examples
phpwordpresswoocommerceproductcart

Disable specific cart item quantity fields based on WooCommerce product category


In woocommerce I am using Hide “remove item” from cart for WooCommerce product category answer code and I would like to disable the cart quantity field too, avoiding customer to change the item quantity to zero.

Is that possible? Any track on this will be appreciated.


Solution

  • The following code will remove the "quantity field" from cart for items from a specific product category (that you will define in the 2nd function):

    // Custom conditional function that handle parent product categories too
    function has_product_categories( $categories, $product_id = 0 ) {
        $parent_term_ids = $categories_ids = array(); // Initializing
        $taxonomy        = 'product_cat';
        $product_id      = $product_id == 0 ? get_the_id() : $product_id;
    
        if( is_string( $categories ) ) {
            $categories = (array) $categories; // Convert string to array
        }
    
        // Convert categories term names and slugs to categories term ids
        foreach ( $categories as $category ){
            $result = (array) term_exists( $category, $taxonomy );
            if ( ! empty( $result ) ) {
                $categories_ids[] = reset($result);
            }
        }
    
        // Loop through the current product category terms to get only parent main category term
        foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
            if( $term->parent > 0 ){
                $parent_term_ids[] = $term->parent; // Set the parent product category
                $parent_term_ids[] = $term->term_id; // (and the child)
            } else {
                $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
            }
        }
        return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
    }
    
    add_filter( 'woocommerce_quantity_input_args', 'hide_cart_quantity_input_field', 20, 2 );
    function hide_cart_quantity_input_field( $args, $product ) {
        // HERE your specific products categories
        $categories = array( 'clothing' );
    
        // Handling product variation
        $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
    
        // Only on cart page for a specific product category
        if( is_cart() && has_product_categories( $product_id, $categories ) ){
            $input_value = $args['input_value'];
            $args['min_value'] = $args['max_value'] = $input_value;
        }
        return $args;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Note: If you are using also your other answer code, the first function is already defined and doesn"t have to be twice on your function php file…