How to change position of woocommerce error messag

2019-03-03 22:04发布

问题:

I am using Woocommerce and would like to position the error message that user's get when they don't enter a required field underneath the form, just before the checkout button.

I tried adding this to my functions.php

add_action( 'woocommerce_review_order_before_payment', 'wc_print_notices', 10  );

but that didn't change the error messages from appearing above the checkout formular.

Which action do I have to remove?

回答1:

To edit the location of the checkout errors you must do the following:

  1. Set SCRIPT_DEBUG constant to true, do it in the wp-config.php file define('SCRIPT_DEBUG', true);
  2. Locate the checkout.js script in the woocommerce/assets/js/frontend
  3. Locate wc_checkout_form.$checkout_form.prepend( error_message ); around line 396
  4. Change it to wc_checkout_form.$order_review.append( error_message );

Setting the SCRIPT_DEBUG to true effectively loads the development resource files rather then the minified production versions, allowing for easy manipulation.

This is not a perfect solution but it works. And now you know where the checkout errors are effectively set in the context of the DOM.



回答2:

You should be able to move it with CSS or physically move the piece of code that calls it into a different div - best to establish a Child Theme if you are going to edit core theme pages/css. There is a call to wc-print_notices(); in templates/checkout/cart-errors.php which you could try putting in wherever you wanted it to print them together with the contents of the page which define the messages. Find the bit that calls the cart-errors.php page part. It should be a wc_get_template('templates/cart-errors.php', .....) call. See also invludes/wc-form-handler.php function checkout_action()

You might find remove_action() instead of add_action() works on 'wc_print_notices' It may cause all sorts of problems though.

Reference https://codex.wordpress.org/Function_Reference/remove_action

wc_print_notices(); also appears in templates/chckout/form-checkout.php - you might also be able to manipulate it or move it there, with the same caveat as above.

The function itself lives in /includes/wc-notice-functions.php. There is also wc_get_notices() which returns an array of error notices which can be echoed out wherever you want them.

This might also be a helpful pointer to the right way to get rid of unwanted messages @XciD 's answer - though OP said it didn't work wc_clear_notices(); might be a useful pointer.

Woocommerce checkout page: remove view cart button & other messages