2015-08-21 31 views
0

我想要做的是顯示除側欄中的相關產品列表中的產品標題以外的價格..但由於某種原因,它不起作用。價格不顯示與WooCommerce在相關產品列表中的常規代碼

是的,我已經搜查了StackOverflow的歸檔和谷歌找到了答案顯而易見:

<?php echo $product->get_price_html(); ?> 

但這個並不在我的代碼結構工作:

<h4>Related products</h4> 
    <ul class="prods-list"> 
    <?php while ($products->have_posts()) : $products->the_post(); ?> 
     <li> 
      <a href="<?php the_permalink(); ?>" target="_blank"> 
      <?php do_action('woocommerce_before_shop_loop_item_title'); ?> 
      <span><?php the_title(); ?></span> 
      /a> 
      </li> 
      <?php endwhile; wp_reset_postdata(); ?> 
    </ul> 

我在做什麼這裏錯了嗎?我試圖在標題跨度後添加代碼,但它不返回任何內容。

回答

0

看起來你正試圖從Post類的Product類中調用一個方法。我無法確定在沒有看到代碼之前,但它看起來像$ products變量被設置爲WP_Query()的一個實例。如果是這樣的話,那麼你需要做兩兩件事:

  1. 使用當前帖子ID
  2. 調用get_price_html()方法的產品對象上獲取一個產品對象的實例

你可以更簡潔地寫出這些,但我會逐一闡述它,解釋每件事情。你的代碼應該是這樣的:

<h4>Related products</h4> 
    <ul class="prods-list"> 
    <?php while ($products->have_posts()) : $products->the_post(); ?> 
     <li> 
     <a href="<?php the_permalink(); ?>" target="_blank"> 
      <?php do_action('woocommerce_before_shop_loop_item_title'); ?> 
      <?php 

      // Get the ID for the post object currently in context 
      $this_post_id = get_the_ID(); 

      // Get an instance of the Product object for the product with this post ID 
      $product = wc_get_product($this_post_id); 

      // Get the price of this product - here is where you can 
      // finally use the function you were trying 
      $price = $product->get_price_html(); 

      ?> 
      <span><?php the_title(); ?></span> 

      <?php 
      // Now you can finally echo the price somewhere in your HTML: 
      echo $price; 
      ?> 

     </a> 
     </li> 
    <?php endwhile; wp_reset_postdata(); ?> 
    </ul> 
+0

工程就像一個魅力。非常感謝,喬希! –

+0

太棒了!你介意將此標記爲接受的答案嗎?它將幫助未來有類似問題的人:-) –

+0

完成。再一次感謝你。 –

相關問題