What I'm trying to do is show the price besides the title of the product in a related products list that is in the sidebar... but it doesn't work for some reason.
Yes, I have searched the StackOverflow archive and Google and found the obvious answer:
<?php echo $product->get_price_html(); ?>
but this one doesn't work in my code structure:
<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>
What am I doing wrong here? I tried adding that code after the title span, but it doesn't return anything.
It looks like you are trying to invoke a method from the Product class on a Post object. I can't tell for sure without seeing code before it, but it looks like the $products variable is set to an instance of WP_Query(). If that's the case, then you need to do two things:
You can write this more succinctly, but I'm going to lay it out piece by piece to explain what each thing does. Your code should look something like this:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.