把它放在你的functions.php中:
function df_add_ticket_surcharge( $cart_object ) {
global $woocommerce;
$specialfeecat = 20763; // category id you want to check for
$spfee = 0.00; // initialize special fee
$spfeeperprod = 0.00; //special fee per product
$found = $false; //required to make the code later only add the item once, also stop loops.
$product_id = 38607; //product id of the one you want to add
foreach ( $cart_object->cart_contents as $key => $value ) {
$proid = $value['product_id']; //get the product id from cart
$quantiy = $value['quantity']; //get quantity from cart
$itmprice = $value['data']->price; //get product price
//check if the desired product is already in cart.
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
}
//check for the category and add desired product
$terms = get_the_terms( $proid, 'product_cat' ); //get taxonomy of the products
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
$catid = $term->term_id;
if($specialfeecat == $catid && ! $found) {
WC()->cart->add_to_cart( 38607 );
}
}
endif;
}
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );
我修改了现有代码中的代码,这就是为什么spfee和spfeeperprod仍在那里,但你并不真正需要它们,这就是为什么我把它们设置为0.我注意到让这段代码工作的缺点是这部分:
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
}
这将检查您要添加的项目的产品ID,该产品ID指定为“$ product_id” . 希望这会有所帮助(我昨天与它斗争了很多,但今天早上终于有了突破!)