Woocommerce - wc_add_notice() not adding to session when nothing in the cart

I have a custom form that calls a function in function.php when submitted. It will eventually check the fields input and either do something or send back an error message using the woocommerce wc_add_notice(), standard stuff.

The problem is, it only seems to add the notice to the session when items have been added to the cart at some point. If I open in an incognito tab and try the form I will get no message. Just to be clear I am using wc_print_notices()in my template.

I have printed out the woocommerce session just to confirm and yep its not in there when nothing has been added to the cart. I have stripped the function right back so it should send back an error message when you click submit regardless of anything filled out or not, just to check. Here is the function in question :

add_action('wp_ajax_add_transfer', 'process_add_transfer');
add_action('wp_ajax_nopriv_add_transfer', 'process_add_transfer');
function process_add_transfer() { global $woocommerce; wc_add_notice( 'This is my custom error', 'error' ); wp_redirect( get_permalink(125) ); //this is the same page form is on
}

link to page here

I have searched and searched and have not come across what I am doing incorrectly or why this isn't working, any help appreciatted.

cheers chris

2 Answers

Ok so I figured it out! It appears that woocommerce 2.1 > does not set a cookie at until the cart is used, to help with caching or something. Here is a thread on it :

Solution for me was to add this to my function :

do_action( 'woocommerce_set_cart_cookies', true );

Hope this helps someone else.

2

You are just adding the error notices here. It will save these errors in session. Now for showing these error notices, you have to use below function on page you are working or from sending ajax request:

wc_print_notices();
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like