问题描述
我需要做什么:我想在将产品添加到购物车之前对产品进行一些检查.更准确地说:我想将我即将添加到购物车的产品与已经添加的产品进行比较,看看是否存在一些冲突.示例:假设我们有一个名为Both shoes"的产品和一个名为left shoes"的产品.用户将左鞋"添加到购物车.然后他添加了双鞋".我想打印错误而不是添加双鞋":抱歉,如果您已将左鞋添加到购物车,则无法添加双鞋.如果你想买双鞋",请先把左鞋"去掉.
What i need to do:I want to run some checks on a product before being added to the cart.More exactly:I want to compare the product i am about to add to the cart, with the ones already added, to see if there are some conflicts.An example:Let's say we have a product named "Both shoes", and a product "left shoe".A user adds "left shoe" to the cart. Then he adds "both shoes". I want to print an error instead of adding the "both shoes": Sorry, but you can't add both shoes if you've added left shoe to the cart. If you want to buy "both shoes", please first remove "left shoe".
我查看了 class-wc-cart.php 并在 811 行找到了一个动作钩子,但为时已晚!这是在添加产品之后
I've looked at class-wc-cart.php and i found an action hook at line 811, but it's too late! It's after the product has been added
"do_action('woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );"
"do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );"
add_to_cart 方法从 705 行开始.http://wcdocs.woothemes.com/apidocs/source-class-WC_Cart.html#705
The add_to_cart method starts at line 705.http://wcdocs.woothemes.com/apidocs/source-class-WC_Cart.html#705
如何在 801 行之前勾住我的产品冲突管理器"功能,又不会黑掉 woocommerce?
How can my "product conflict manager" function be hooked before line 801, without hacking woocommerce?
谢谢!
推荐答案
有点晚了,但我认为您正在寻找可过滤的添加到购物车验证.这是一个过度简化的版本:
A bit late, but I think you are looking for add to cart validation, which is filterable. Here's an over simplified version:
function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {
// do your validation, if not met switch $passed to false
if ( 1 != 2 ){
$passed = false;
wc_add_notice( __( 'You can not do that', 'textdomain' ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );
这篇关于WordPress.电子商务.添加到购物车之前的操作挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!