如何在Woocommerce中为每个品牌创建购物车



所以我正在使用Woo Brand插件来显示我在商店中使用的所有品牌。 我想做的是限制客户一次从多个品牌购买。例如,如果我有品牌 A 和品牌 B,则客户只能从品牌A或只能从品牌B将产品添加到购物车。 如果他们的购物篮中只有来自品牌 A 的产品,并且他们转到品牌 B 的页面,那么在品牌 B 的页面上,我想有一个新购物篮,他们只能在其中添加品牌 B 的产品。如果他们从品牌 A 返回页面,他们的购物车中仍将包含仅从品牌 A 添加的产品。我怎样才能做到这一点?

目前我有这段代码,它只能从特定品牌添加到购物车中,例如(如果我在品牌 A 页面上,我只能从他们添加(

add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_brand_allowed', 20, 3 );
function only_one_product_brand_allowed( $passed, $product_id, $quantity) {
// Getting the product brand term slugs in an array for the current product
$brand_slugs = wp_get_post_terms( $product_id, 'product_brand', array( 'fields' => 'slugs' ) );

$cart_contents = WC()->cart->get_cart();
$cart_item_keys = array_keys ( $cart_contents );
// Get the brand name for first item from cart
$first_item = $cart_item_keys[0];
$first_item_id = $cart_contents[$first_item]['product_id'];
$brand_name = get_the_terms($first_item_id, 'product_brand');
$current_product_brand = get_the_terms($product_id, 'product_brand');


// Loop through cart items
foreach ($cart_contents as $cart_item_key => $cart_item ){
// Check if the product category of the current product don't match with a cart item
if( ! has_term( $brand_slugs, 'product_brand', $cart_item['product_id'] ) ){
// phpAlert('Trebuie golit cosul');
// Displaying a custom notice
wc_add_notice( __('You can add products to the cart only from the same brand. In your cart are products from <strong>'.$brand_name[0]->name. '.' ), 'error' );
// Avoid add to cart
return false; // exit
}
}
return $passed;
}

您不能在WooCommerce中为每个产品品牌使用不同的购物篮(购物车(,您只能避免客户组合来自不同品牌的商品并优化您的代码,例如:

add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_brand_allowed', 20, 3 );
function only_one_product_brand_allowed( $passed, $product_id, $quantity) {
$taxonomy    = 'product_brand';
$field_names = array( 'fields' => 'names');
// Getting the product brand term name for the current product
if( $term_name = wp_get_post_terms( $product_id, $taxonomy, $field_names ) ) {
$term_name = reset($term_name);
} else return $passed;

// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item ){
// Get the cart item brand term name
if( $item_term_name = wp_get_post_terms( $cart_item['product_id'], $taxonomy, $field_names ) ) {
$item_term_name = reset($item_term_name);
} else continue;
// Check if the product brand of the current product exist already in cart items
if( isset($term_name) && isset($item_term_name) && $item_term_name !== $term_name ){
// Displaying a custom notice 
wc_add_notice( sprintf( __("You are not allowed to combine products from different brands. There is already a cart item from <strong>%s</strong> brand.", "woocommerce" ), $item_term_name ), 'error' );
// Avoid add to cart and display message
return false;
}
}
return $passed;
}

代码进入函数.php活动子主题(或活动主题(的文件。经过测试并工作。

现在,您可以做的是在多个子订单中吐出一个订单,每个品牌(或商家(一个子订单,保留原始订单。

最新更新