相关产品列表中的 WooCommerce 常规代码未显示价格

The price doesn't show up with the regular code from WooCommerce in a related products list

我想做的是在侧边栏的相关产品列表中显示产品标题以外的价格...但由于某种原因它不起作用。

是的,我搜索了 Whosebug 存档和 Google 并找到了显而易见的答案:

<?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>

我在这里做错了什么?我尝试在标题范围之后添加该代码,但它没有 return 任何东西。

您似乎正试图从 class 对象的 Post 对象调用方法。如果没有看到之前的代码,我无法确定,但看起来 $products 变量被设置为 WP_Query() 的一个实例。如果是这样,那么你需要做两件事:

  1. 使用当前 Post ID 获取 Product 对象的实例
  2. 对 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' ); ?>
          <?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>