Home > Software design >  Add fee if product variant is in cart
Add fee if product variant is in cart

Time:11-24

I am trying add fee( 50) to order if user have in cart specific product with specific variant ID. In cart and checkout page should also display custom text. This is my current code:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_discount', 30, 1 );
function shipping_weight_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    $percentage    = 0;
    $product_id = 1761;
    $variation_id = 1853;
    $cart_id = WC()->cart->generate_cart_id( $product_id, $variation_id);
    if( WC()->cart->find_product_in_cart( $cart_id ) ) {
    $percentage = 50;
}
    

    if( $percentage > 0 ) {
        $discount = $percentage;
        $cart->add_fee( sprintf( __( 'Množstevní sleva %s', 'woocommerce' ), $percentage.'%'),  $discount );
    }
}

seems $percentage is 0 and it is reason, why is not fee apllied

CodePudding user response:

Please try below code:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_discount', 30, 1 );
function shipping_weight_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    $percentage    = 0;
    $product_id = Your_product_id;
    $variation_id = Your_variation_id;
  if( in_array( $product_id, array_column( WC()->cart->get_cart(), 'product_id' ) ) && in_array( $variation_id, array_column( WC()->cart->get_cart(), 'variation_id' ) ) ) {
    $percentage = 50;
}
    

    if( $percentage > 0 ) {
        $discount = $percentage;
        $cart->add_fee( sprintf( __( 'Množstevní sleva %s', 'woocommerce' ), $percentage.'%'),  $discount );
    }
}

It is tested and working good.

Please don't forget to update the product id AND variation id in the above code

Please let me know if you find any issues.

  • Related