Skip to main content
2 of 3
added 4 characters in body
mantis
  • 790
  • 2
  • 18
  • 38

Creating array to compare custom field values

I think I need some guidance here. I have a list of custom posts on a an archive template page that displays information from each of the custom posts. They are looped through using WPQuery:

<?php $restypes = new WP_Query( array( 'post_type' => 'reservation_type', 'posts_per_page' => -1 ) );?>

Each post has a several custom fields: $price, an optional $promo_price and a variable $per which determines if the price is per-person or per-room based on a custom taxonomy. The best price is then determined like so:

  if(in_array( 'dorm', $per )){
      $person_room ='per-person';
  } else {
      $person_room ='per-room';
  }  
    
  $post_id= $post->ID;
  $promo_price = get_field('promo_price');
  $norm_price = get_field('price');
  $p_per_room = get_field('people_per_room');
  
  if ($promo_price && !empty($promo_price)){
        
        if($person_room == 'per-room'){
            $addprice= $promo_price /$p_per_room;
        } else {
            $addprice= $promo_price;
        }
 
        $prices[$post_id]= $addprice;
        
  } elseif ($norm_price && !empty($norm_price)){
        
        if($person_room == 'per-room'){
            $addprice= $norm_price /$p_per_room;
        } else {
            $addprice= $norm_price;
        }
        
        $prices[$post_id]= $addprice;
  }
  
  $best = array_keys($prices, min($prices));

My problem is that the array $best is not complete until all the posts have been looped through. The point of all this is to be able to add:

<?php
if(in_array($post->ID, $best)){?> 
<div class="best-price"> 
<div class="ribbon-wrapper"><div class="ribbon">Best Price</div></div>
<?php  } else { ?>
    <div>
<?php } ?>

thus giving a different style to the item with the best price per-person.

My question is would I need to create a separate loop to populate the $best array in order to do this? Or is there a better way to do this?

I was thinking initially of using the orderby => 'meta_value_num' having calculated the best price as a function and adding a meta value.

PS The get_field() function comes from Advanced custom fields.

mantis
  • 790
  • 2
  • 18
  • 38