WooCommerce - Calculation of conditional baskets based on subcategories

I have a very specific project and I need another basket rule. I could not find a plugin or any other resource on how to achieve this.

I have subcategory 1 (i.e. tables) and subcategory 2 (i.e. chairs). Users can add only 1 product from the sub-categories of the Table , which is required, and as many products as they want, from the sub-categories of the Department , which are not required.

I need the following rule: . If users also added products from subcategories of the subcategory , then subtract the total cost of the products of the subcategories Chairs from the subcategory of the Tables . Also in this case, if the price is <0, then set the value to 0.

Does anyone know how I can do this using standard WordPress Woocommerce?

+4
source share
1 answer

It’s possible to do this job by adding a discount to the cart based on requirements and subcategory calculations ...

The code:

add_action( 'woocommerce_cart_calculate_fees','table_chairs_cart_discount', 10, 1 );
function table_chairs_cart_discount($cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Initializing variables
    $chairs_total = 0;
    $table_total = 0;
    $discount = 0;

    // Iterating through each cart item
    foreach($cart_object->get_cart() as $item_key => $item):

        $item_line_total = $item["line_total"]; // Item total price (price x quantity)

        // Chairs subcategory items
        if(has_term('chairs', 'product_cat', $item['product_id']))
            $chairs_total += $item_line_total;

        // Table subcategory items
        if(has_term('table', 'product_cat', $item['product_id']))
            $table_total += $item_line_total;

    endforeach;

    // ## CALCULATIONS ##
    if( $table_total <= $chairs_total && $chairs_total > 0 ) 
        $discount -= $table_total;
    elseif ($chairs_total > 0) 
        $discount -= $chairs_total;

    // Adding the discount
    if ($discount != 0)
        $cart_object->add_fee( __( 'Chairs discount', 'woocommerce' ), $discount, false );
        // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}

The code goes in the function.php file of your active child theme (or theme). Or also in any php file plugins.


:

+1

Source: https://habr.com/ru/post/1662971/


All Articles