2017-10-08 40 views
1

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

下面是我的一些代码:

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

什么我需要添加到显示短码被使用在页面上的错误信息?

回答

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; ...
  • 请记住,在简码你永远不回声或打印任何东西,但你返回一些输出...
  • 不要忘记在最后重置循环和查询。
相关问题