Search code examples
phpwordpresswoocommercecartdiscount

Deposit on backordered cart items in WooCommerce


I've taken this code from another post and basically this code is trying to force the cart price with a discount.

What I want to do is force the discount only if the product is on backorder. So if product is on backorder, the client can order this item which leads to a deposit calculation in the cart.

From Deposit based on a percentage of total cart amount 2nd code snippet answer, I have tried to make code changes to get a specific discount on backordered cart items.

The original code works fine as it's, but how to make it work only for backordered items?

I tried several days now using for example $product->is_on_backorder( 1 ) but I can't get it to work. How to get backordered items total amount in cart?

I know it's an easy solution, but I have tried several solutions and can't get it to work.


Solution

  • Updated: To make that for backordered items only, you will use the following:

    add_action( 'woocommerce_cart_calculate_fees', 'calculated_deposit_discount_on_backorders' );
    function calculated_deposit_discount_on_backorders( $cart ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        ## Set HERE your negative percentage (to remove an amount from cart total)
        $percent = -.80; // 80% off (negative)
    
        $backordered_amount = 0;
    
        foreach( $cart->get_cart() as $cart_item ) {
            if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
                $backordered_amount = $cart_item['line_total'] + $cart_item['line_tax'];
            }
        }
    
        ## ## CALCULATION ## ##
        $calculated_amount = $backordered_amount * $percent;
    
        // Adding a negative fee to cart amount (Including taxes)
        $cart->add_fee( __('Deposit calculation', 'woocommerce'), $calculated_amount, true );
    
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should work.