Search code examples
wordpresswoocommerceadvanced-custom-fields

How to display related product price on another single product page


I would like to display few related products on a single product page, custom picked. I am using ACF plugin with Relations field. I am trying this code but it returns current product price, rather than the related products prices (in foreach):

<?php 
   $product = new WC_Product(get_the_ID()); 
  echo wc_price($product->get_price_including_tax(1,$product->get_price()));
?>

the code works fine on static pages, and prices for few related products are correct, but not on a single page product. I thought that the part get_the_ID() handles targeting of specific post?

UPDATE:

Here is my whole code including ACF relation field:

<?php 
    $posts = get_field('related_set_1');
    if( $posts ): ?>
<?php foreach( $posts as $p): ?>
    <li>
        <a href="<?php echo get_permalink( $p->ID ); ?>">
            <?php 
              echo get_the_post_thumbnail( $p->ID, '175x100' )
                    ?>
                <div style="overflow:hidden">
                    <h4><?php echo $p->post_title; ?></h4>
                    <p class="price">
                        <?php 
                        global $post;
                        $product = new WC_Product($post->ID); 
                        echo wc_price($product->get_price_including_tax(1,$product->get_price()));
                        ?>
                    </p>
                    <p class="link">View now</p>
                </div>
        </a>
    </li>
    <?php endforeach; ?>
        <?php endif; ?>

I also added global $post; from reply below but I still have the same output: the price displayed is the price of the product on the page where the code is placed, not the product in the 'related items' grid.

And I use this in functions.php in filter function, if that makes any difference?

add_filter( 'woocommerce_after_single_product_summary', 'custom_related_products' );
function custom_related_products() { ?>
.... (the code above here)
<php? }

everything works well, apart the price.


Solution

  • get_the_ID() works only when there is a WordPress loop. The usage of the WordPress loop depends on the theme that's you're using.

    For a single post, it's highly likely a WordPress loop isn't being used by the theme. A more reliable way of doing this is by calling the global $post and then accessing the post ID by $post->ID.

    <?php 
    global $post;
    $product = new WC_Product($post->ID); 
    echo wc_price($product->get_price_including_tax(1,$product->get_price()));
    ?>