John Davidson

php - Woocommerce fee not multiplying on multiple cart items?

0 comments
Message:


This script is adding a fee if the product is in a particular category.

The script is working but only for one cart item.

But if there are 2 or more items it wil not multiply in the cart.

What am I doing wrong?


add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

// iPhone CAT
$iphone_categories = array('74');
$iphone_fee_amount = 0;

// iPad CAT
$ipad_categories = array('75');
$ipad_fee_amount = 0;


// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
$quantiy = $cart_item['quantity']; //get quantity from cart
if( has_term( $iphone_categories, 'product_cat', $cart_item['product_id']) )
$iphone_fee_amount = 4.70 * $quantiy;
if( has_term( $ipad_categories, 'product_cat', $cart_item['product_id']) )
$ipad_fee_amount = 2.60 * $quantiy;
}

// Adding the fee for iPhone
if ( $iphone_fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Thuiskopieheffing iPhone", "woocommerce" ), $iphone_fee_amount, true );
}
// Adding the fee for iPad
if ( $ipad_fee_amount > 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Thuiskopieheffing iPad", "woocommerce" ), $ipad_fee_amount, true );
}
}


My Answer:
) return; // Exit if in admin

$category_id = 15; // Category ID for which fee should be applied
$fee_amount = 5; // Fee amount

$total_fee = 0;

foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$product_cat_ids = wc_get_product_term_ids( $product_id, 'product_cat' );

if ( in_array( $category_id, $product_cat_ids ) ) {
$total_fee += $fee_amount;
}
}

if ( $total_fee > 0 ) {
$cart->add_fee( 'Category Fee', $total_fee, true );
}
}

Rate this post

5 of 5 based on 7824 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us