WordPress。电子商务。添加到购物车之前的操作挂钩

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14428248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:08:40  来源:igfitidea点击:

Wordpress. Woocommerce. Action hook BEFORE adding to cart

wordpresshookwoocommerce

提问by Sergiu-Antonin Ghita

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".

我需要做什么:我想在将产品添加到购物车之前对产品进行一些检查。 更准确地说:我想比较我即将添加到购物车的产品和已经添加的产品,看看是否存在一些冲突。 一个例子:假设我们有一个名为“Both shoes”的产品和一个名为“left shoes”的产品。用户将“左鞋”添加到购物车。然后他添加了“双鞋”。我想打印错误而不是添加“双鞋”:抱歉,如果您将左鞋添加到购物车,则无法添加双鞋。如果您想购买“双鞋”,请先将“左鞋”取下。

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

我查看了 class-wc-cart.php 并在第811行找到了一个动作挂钩,但为时已晚!这是在添加产品之后

"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 );"

The add_to_cart method starts at line 705. http://wcdocs.woothemes.com/apidocs/source-class-WC_Cart.html#705

add_to_cart 方法从第705行开始。 http://wcdocs.woothemes.com/apidocs/source-class-WC_Cart.html#705

How can my "product conflict manager" function be hooked before line 801, without hacking woocommerce?

我的“产品冲突管理器”功能怎么能在801线之前被勾住,又不会黑掉woocommerce?

Thank you!

谢谢!

回答by helgatheviking

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 );