Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress. Woocommerce. Action hook BEFORE adding to cart

Tags:

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

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

The add_to_cart method starts at line 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?

Thank you!

like image 905
Sergiu-Antonin Ghita Avatar asked Jan 20 '13 19:01

Sergiu-Antonin Ghita


People also ask

How do I use WooCommerce hooks in WordPress?

To use WooCommerce hooks (or WordPress hooks in general), you'll need to add code to your site. But again, you do not need to edit the template files themselves – you can add this code all in the same spot. There are two places you can add this code: Your child theme's functions.


1 Answers

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 ); 
like image 89
helgatheviking Avatar answered Dec 02 '22 07:12

helgatheviking