skip to Main Content

I’m using the ACF post object field to display multiple Woocommerce products as post type items. However, I’m trying to only display the prices of these selected products as a min/max price range (eg. $21.95 – $58.50).

Here is the code I’m using for the loop but it just shows every price. Is there a way to just show the lowest and highest price as a price range?

<?php
$linked_products = get_field('linked_products');
if( $linked_products ): ?>
    <?php foreach( $linked_products as $post ): 
        setup_postdata($post); ?>
        <?php $product = wc_get_product( $post ); $prices = $product->get_price_html(); echo $prices; ?>
    <?php endforeach; ?>
<?php 
wp_reset_postdata(); ?>
<?php endif; ?>

2

Answers


  1. Maybe you could set php variables and store lowest and highest price in those variables

    <?php
    $linked_products = get_field('linked_products');
    
    if( $linked_products ): ?>
        <?php foreach( $linked_products as $post ): 
            setup_postdata($post);
            if(!isset($lowest_price) || $product->get_price() < $lowest_price) {
              $lowest_price = $product->get_price();
            }
            if(!isset($highest_price) || $product->get_price() > $highest_price) {
              $highest_price = $product->get_price();
            }
            ?>
            <?php $product = wc_get_product( $post ); $prices = $product_price; echo $prices; ?>
        <?php endforeach; ?>
    <?php 
    wp_reset_postdata(); ?>
    <?php endif; ?>
    
    
    Login or Signup to reply.
  2. Try the following code. It displays the prices range as lowest price to highest price:

    <?php
    $linked_products = get_field('linked_products');
    $lowest_price = 100000;
    $highest_price = 0;
    if( $linked_products ): ?>
        <?php foreach( $linked_products as $post ): 
            setup_postdata($post); ?>
            <?php 
                $product = wc_get_product( $post ); 
                $prices = $product->get_price_html(); 
                $prices = str_replace("$", "", $prices);
                if ($prices > $highest_price) $highest_prices = $prices
                else if ($prices < $lowest_price) $lowest_prices = $prices 
            ?>
        <?php endforeach; ?>
        <?php
           echo "$". $lowest_price . " - " . "$". $highest_price;
        ?>
    <?php 
    wp_reset_postdata(); ?>
    <?php endif; ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search