Show woocommerce errors

Viewed 8583

I have a woocommerce store and want to show wocommerce error messages in specific place of my theme, for example under submit button.

I know wocommerce error messages come from here:

<ul class="woocommerce-error">
<?php foreach ( $messages as $message ) : ?>
    <li><?php echo wp_kses_post( $message ); ?></li>
<?php endforeach; ?>
</ul>

But, when i put this code in my page (for example edit-my-address.php page), its giving error! What is working or simple code for showing messages in woocommerce? Thanks in advance.

4 Answers

you can use both methods here..

woocommerce_show_messages();
wc_print_notices(); 

You can also show woocommerce custom notices according to your condition like...

wc_add_notice( 'This is a Success notice', 'success' );
wc_add_notice( 'This is a Error notice', 'error' );
wc_add_notice( 'This is a \'Notice\' notice\'', 'notice' );

You can add this piece of code to functions.php of your child theme

add_shortcode('woocommerce_notices', function($attrs) {
    if (wc_notice_count() > 0) {
    ?>

    <div class="woocommerce-notices-shortcode woocommerce">
    <?php wc_print_notices(); ?>
    </div>

    <?php
    }
});

And then use it as a shortcode [woocommerce_notices] in any desired post or page, or use <?php echo do_shortcode('[name_of_shortcode]'); ?> in a desired PHP template.

Tested and works. Good luck.

A bit late to the party but here is a solution.

Try to use the following piece of code (taken from the original file here: wp-content/plugins/woocommerce/templates/single-product.php)

<?php
  /**
   * woocommerce_before_main_content hook.
   *
   * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
   * @hooked woocommerce_breadcrumb - 20
   */
  do_action( 'woocommerce_before_main_content' );
?>

Hope it helps

you missed to add this line of code:

<?php wc_print_notices(); ?>
Related