Search code examples
phpwordpresswoocommerceshortcodeproduct

Display Woocommerce notices on a page


I have created a function to display some products with a shortcode, but the problem I am having is that the errors messages are not shown on that page. For example if some fields are required then it's only displayed on the cart/checkout page.

Here's some of my code:

while ( $query->have_posts() ) : $query->the_post();
global $product;
?>
<div style="border-bottom:thin dashed black;margin-bottom:15px;">
<h2><?php the_title(); ?>  <span><?php echo $product->get_price_html();?></span></h2>
<p><?php the_excerpt();?></p>
<?php global $product;
if( $product->is_type( 'simple' ) ){
woocommerce_simple_add_to_cart();
}

What do I need to add to show the error messages on the page the shortcode is being used on?


Solution

  • You need to use dedicated wc_print_notices() function, that displays Woocommerce notices. This function is hooked or used in woocommerce templates for that purpose.

    To make the WooCommerce notice actives in the page of your short code you need to add inside your shortcode this wc_print_notices() function.

    I have reproduced a similar Shortcode as yours below (for testing purpose) where woocommerce notices are printed:

    if( !function_exists('custom_my_products') ) {
        function custom_my_products( $atts ) {
            // Shortcode Attributes
            $atts = shortcode_atts( array( 'ppp' => '12', ), $atts, 'my_products' );
    
            ob_start();
            
            // HERE we print the notices
            wc_print_notices();
    
            $query = new WP_Query( array(
                'post_type'      => 'product',
                'posts_per_page' => $atts['ppp'],
            ) );
    
            if ( $query->have_posts() ) :
                while ( $query->have_posts() ) :
                    $query->the_post();
                    global $product;
                ?>
                    <div style="border-bottom:thin dashed black;margin-bottom:15px;">
                    <h2><?php the_title(); ?>  <span><?php echo $product->get_price_html();?></span></h2>
                    <p><?php the_excerpt();?></p>
                <?php
                    if( $product->is_type( 'simple' ) )
                        woocommerce_simple_add_to_cart();
    
                endwhile;
            endif;
            woocommerce_reset_loop();
            wp_reset_postdata();
    
            return '<div class="my-products">' . ob_get_clean() . '</div>';
        }
        add_shortcode( 'my_products', 'custom_my_products' );
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This is tested and works on WooCommerce 3+

    Notes:

    • In your code you are using 2 times global $product;
    • Remember that in a shortcode you never echo or print anything, but you return some output…
    • Don't forget to reset the loop and the query at the end.