1 回答
TA贡献1872条经验 获得超3个赞
以下内容仅允许将来自一个“供应商”的商品添加到购物车:
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;
}
现在,为了确保客户无法向购物车中的不同供应商结帐,您可以添加以下内容:
// 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' );
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报