Reputation: 49
I am struggling with a function to add fees to a Woocommerce Subscription, based on the number of other products in the cart. When I run it I get a critical error on the site. Can anyone see why?
add_filter( 'woocommerce_cart_calculate_fees', 'add_administration_fees', 10, 1 );
function add_administration_fees( $cart ) {
/* First I try to sum the number of products in the cart that are NOT subscriptions */
$item_count = 0;
foreach ( WC()->cart->get_cart() as $item ) {
if (!$item->is_type('subscription')) {
$item_count++;
}
}
/* Then I try to add $50 per extra product to the Initial Order Fee */
if ( empty( $cart->recurring_cart_key ) ) {
$cart->add_fee( 'Additional Items', $item_count * 50 );
}
/* Then I try to add $7 per extra product to the Recurring Monthly Fee (if the cart is on page 254) or $5 per extra product (if the cart is on page 457) */
if ( is_page(254)) {
if ( ! empty( $cart->recurring_cart_key ) ) {
$cart->add_fee( 'Additional Items', $item_count * 7 );
}
}
if ( is_page(457)) {
if ( ! empty( $cart->recurring_cart_key ) ) {
$cart->add_fee( 'Additional Items', $item_count * 5 );
}
}
}
Upvotes: 0
Views: 237
Reputation: 2086
There are few problems with your code.
This hook is used on cart and checkout page and is_page(some ID) doesnt make sense.
$item is not product object so you cant use is_type()
Since its unclear what you are trying to do this should be a good starting point
add_filter( 'woocommerce_cart_calculate_fees', 'add_administration_fees' );
function add_administration_fees() {
if(!WC()->cart->is_empty()) {
$item_count = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// We need product object
$product = $cart_item['data'];
//replace with w.e product type you want
if(!$product->is_type('subscription')) {
$item_count++;
}
}
//Add fee only if we have products other than subscription
if($item_count > 0) {
WC()->cart->add_fee( 'Additional Items', $item_count * 50 );
}
}
}
Upvotes: 1