我有這個代碼,我試圖檢查購物車是否包含兩個類別的產品;飲料和捆綁。如果為真,則應用 -1 的費用。
目前它正在作業,但不太正確,因為它正在檢查購物車是否包含 EITHER Drinks OR Bundles。
我需要它來檢查兩個類別是否都在購物車中,而不僅僅是一個。我確定這是我遺漏的簡單東西?
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Categories in a coma separated array
$categories = array('drinks','bundles');
$fee_amount = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
$fee_amount = -1;
}
// Adding the fee
if ( $fee_amount < 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}
uj5u.com熱心網友回復:
您可以迭代$cart->get_cart()使用 get category的回圈get_the_terms()并將其推送到陣列,然后您可以回圈$must_categories檢查兩個類別是否可用。
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
function custom_pcat_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Categories in a coma separated array
$must_categories = array('drinks','bundles');
$fee_amount = 0;
$product_cat = array();
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
$terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
foreach ($terms as $term) {
$product_cat[] = $term->slug;
}
}
array_unique( $product_cat );
foreach ( $must_categories as $key => $must_cat ) {
if( in_array($must_cat, $product_cat) ){
$fee_amount = -1;
}else{
$fee_amount = 0;
break;
}
}
// Adding the fee
if ( $fee_amount < 0 ){
// Last argument is related to enable tax (true or false)
WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}
測驗和作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/336504.html
標籤:php WordPress的 求购 大车
