提问者:小点点

根据WooCommerce产品类别禁用特定购物车项目数量字段


在woocommerce中,我使用Hide“remove item”from cart for woocommerce产品类别回答代码,并且我想禁用cart quantity字段,避免客户将商品数量更改为零。

可能吗?任何关于这方面的线索都将不胜感激。


共1个答案

匿名用户

以下代码将从购物车中删除特定产品类别(您将在第2个函数中定义)中的项目的“数量字段”:

// 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;
}

代码function.php活动子主题(或活动主题)的文件中。测试和工作。

注意:如果您也在使用其他答案代码,那么第一个函数已经定义,并且不必在函数php文件中出现两次…