0
votes

I am creating a woocommerce function that allows me to add a specific product to the cart based on the following conditions:

  1. specific categories

  2. total cost of the products higher than a value that I have defined in $ min_price

I was able to get that based on the category, woocommerce adds the indicated product. Unfortunately I can't describe the flow that does this when the total value of the products is higher than the $ min_price.

Can anyone help me? Thanks

    add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
    function auto_add_item_based_on_product_category( $cart ) {

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
        
    $min_price     = 77.47; // The minimal cart amount

    $required_categories = array('computer-based', 'esami-paper-based'); // Required product category(ies)
    $added_product_id = 5065; // Specific product to be added automatically
    $matched_category = false;
    $matched_subtotal = false;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item_key => $item ) {
        // Check for product category
        if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
            $matched_category = true;
        }
        // Check if specific product is already auto added
        if( $item['data']->get_id() == $added_product_id ) {
            $saved_item_key = $item_key; // keep cart item key
        }
        // Check it the minimum subtotal is reached
        if ( !empty( $product_subtotal > $min_price ) ) {
            $matched_subtotal = true;
        }
    }

    // If specific product is already auto added but without items from product category and minimun subtotal is not reached
    if ( isset($saved_item_key) && ! $matched_category && ! $matched_subtotal ) {
        $cart->remove_cart_item( $saved_item_key ); // Remove specific product
    }
    // If there is an item from defined product category and subtotal reached and specific product is not in cart
    elseif ( ! isset($saved_item_key) && $matched_category && $matched_subtotal ) {
        $cart->add_to_cart( $added_product_id ); // Add specific product
    }
}