在页面上显示 Woocommerce 通知

Display Woocommerce notices on a page

我已经创建了一个功能来显示一些带有短代码的产品,但我遇到的问题是错误消息没有显示在该页面上。例如,如果某些字段是必需的,那么它只会显示在 cart/checkout 页面上。

这是我的一些代码:

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();
}

我需要添加什么才能在使用短代码的页面上显示错误消息?

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.

要使 WooCommerce 通知在您的短代码页面中激活,您需要在短代码中添加此 wc_print_notices() 函数。

我在下面复制了一个与您的相似的简码 (用于测试目的) 其中打印了 woocommerce 通知:

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' );
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

这已经过测试并适用于 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.