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



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 ?

  • 1
    when you call cart->add_to_cart, that calls the action woocommerce_add_to_cart again. to avoid that, test the cart content and change it only if needed. – Kaperto Nov 8 '19 at 13:05
  • @Kaperto Ok, thanks, that´s clearer now, so to empty the cart and add just one product from $_POST, what hook should I use ? Or should I use another method of WC()->cart ? – J.BizMai Nov 8 '19 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.