Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 965
chrisPbacon Avatar asked Dec 24 '22 08:12

chrisPbacon


1 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 : https://github.com/woothemes/woocommerce/issues/4920

Solution for me was to add this to my function :

do_action( 'woocommerce_set_cart_cookies',  true );

Hope this helps someone else.

like image 100
chrisPbacon Avatar answered Dec 28 '22 10:12

chrisPbacon