【发布时间】:2017-11-28 12:35:51
【问题描述】:
我正在使用 WC Marketplace 经营一家 WooCommerce 商店。我试图用下面的钩子实现的是,如果篮子里已经有来自不同供应商的产品,则防止将新项目添加到篮子中。例如如果购物者将供应商 y 的产品 x 添加到他的购物篮中,如果他们要添加供应商 b 的产品 a,则该商品将不会被添加,并且会通知用户错误。
我有两个问题:
- 首先钩子什么时候运行,是在主函数触发之前还是之后?我有一个函数woocommerce_add_to_cart 的钩子。所以我想知道函数woocommerce_add_to_cart运行之后或者之前钩子会触发。
- 我的第二个问题是,我附上了下面的钩子,您认为这可行吗?
function action_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
$same_vendor = 1;
$empty = WC_Cart::is_empty();
//If there is an item in the cart then,
if (!$empty) {
//Get the VendorId of the product being added to the cart.
$vendor = get_wcmp_product_vendors($product_id);
$vendor_id = $vendor->id;
foreach( WC()->cart->get_cart() as $cart_item ) {
//Get the vendor Id of the item
$cart_product_id = $cart_item['product_id'];
$cart_vendor = get_wcmp_product_vendors($product_id);
$cart_vendor_id = $cart_vendor->id;
//If two products do not have the same Vendor then set $same_vendor to 0
if($vendor_id !== $cart_vendor_id) {
$same_vendor = 0;
}
}
if ($same_vendor === 0) {
WC()->cart->remove_cart_item( $cart_item_key );
//How do I show a message to tell the customer.
}
}
}
问候
【问题讨论】:
-
基本上你希望用户在购物车中只添加一个产品?
-
不,我希望他们只将来自 1 个供应商的产品添加到购物车。
标签: php wordpress woocommerce cart hook-woocommerce