2017-10-08 113 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; ...
  • 請記住,在簡碼你永遠不回聲或打印任何東西,但你返回一些輸出...
  • 不要忘記在最後重置循環和查詢。
相關問題