【问题标题】:Is there a way to display numerical values in a foreach loop as "Min - Max"?有没有办法在 foreach 循环中将数值显示为“Min - Max”?
【发布时间】:2021-05-24 06:50:12
【问题描述】:

我正在使用 ACF 帖子对象字段将多个 Woocommerce 产品显示为帖子类型项目。但是,我试图仅将这些选定产品的价格显示为最低/最高价格范围(例如 21.95 美元 - 58.50 美元)。

这是我用于循环的代码,但它只显示每个价格。有没有办法仅将最低和最高价格显示为价格范围?

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

【问题讨论】:

    标签: php wordpress woocommerce advanced-custom-fields


    【解决方案1】:

    也许您可以设置 php 变量并在这些变量中存储最低和最高价格

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

    【讨论】:

      【解决方案2】:

      试试下面的代码。它将价格范围显示为最低价到最高价:

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

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2017-09-11
        • 2010-12-01
        • 1970-01-01
        • 2019-08-24
        • 2014-11-12
        • 2021-04-22
        • 2010-12-19
        • 1970-01-01
        相关资源
        最近更新 更多