I´m trying to do specific action when the user add to cart for a WooCommerce Variation product.
This is my code inside a Class :
My Class {
...
public function init(){
add_action('woocommerce_add_to_cart', array( $this, 'custom_add_to_cart' ), 10 );
}
function custom_add_to_cart() {
global $woocommerce;
if( !empty( $_POST )
&& !empty( $_POST['product_id'] )
&& !empty( $_POST['variation_id'] )
){
if( !WC()->cart->is_empty() ){
WC()->cart->empty_cart( true );
}
var_dump( $_POST );
WC()->cart->add_to_cart( $_POST['product_id'], 1, $_POST['variation_id'] );
exit;
}
}
}
For some reasons, when I click on "add to cart" button, my function is called several times, maybe inside a loop until to get this error :
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes) ....
What I should do to call this function just once ?