在页面上显示Woocommerce通知

时间:2017-10-08 14:02:48

标签: php wordpress woocommerce shortcode product

我创建了一个显示一些带有短代码的产品的功能,但我遇到的问题是该页面上没有显示错误消息。例如,如果需要某些字段,则它仅显示在购物车/结帐页面上。

这是我的一些代码:

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

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

1 个答案:

答案 0 :(得分:2)

  

您需要使用专用的wc_print_notices()功能,该功能会显示Woocommerce通知。为此目的,此功能在woocommerce模板中被挂钩或使用。

要在短代码页面中激活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 +

  

注意:

     
      
  • 在您的代码中,您使用了2次global $product; ...
  •   
  • 请记住,在短代码中,您永远不会回显或打印任何内容,但返回某些输出...
  •   
  • 不要忘记在最后重置循环和查询。
  •