1 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
以下內(nèi)容僅允許將來自一個(gè)“供應(yīng)商”的商品添加到購物車:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_supplier_by_order', 10, 2 );
function only_one_supplier_by_order( $passed, $product_id ) {
if ( WC()->cart->is_empty() )
return $passed;
$taxonomy = 'supplier';
$term_ids = wp_get_post_terms( $product_id, $taxonomy, ['fields' => 'ids']);
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
if( ! has_term( $term_ids, $taxonomy, $cart_item['product_id'] ) ) {
// Displaying a custom notice
wc_add_notice( __('This product is with a different supplier. Please only order from 1 supplier at a time.'), 'error' );
return false; // Avoid add to cart
}
}
return $passed;
}
現(xiàn)在,為了確??蛻魺o法向購物車中的不同供應(yīng)商結(jié)帳,您可以添加以下內(nèi)容:
// To be sure (avoiding checkout)
add_action( 'woocommerce_check_cart_items', 'only_one_supplier_by_order_check' );
function only_one_supplier_by_order_check() {
$taxonomy = 'supplier';
$term_names = []; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
$terms = wp_get_post_terms( $cart_item['product_id'], $taxonomy );
if( ! empty($terms) ) {
$term = reset($terms);
$term_names[$term->term_id] = $term->name;
}
}
// Allow only one supplier in cart (avoid checkout for more than one
if( count( $term_names ) > 1 ) {
// Displaying a custom notice
wc_add_notice( __('Only items from one supplier at the time are allowed in cart'), 'error' );
}
}
代碼位于活動(dòng)子主題(或活動(dòng)主題)的functions.php 文件中。經(jīng)過測(cè)試并有效。
- 1 回答
- 0 關(guān)注
- 139 瀏覽
添加回答
舉報(bào)