2015-08-21 30 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

完成。再一次感谢你。 –

相关问题