i want to display wordpress posts by a custom field value. That's not that hard. I've got that already:
<?php
// args
$args = array(
'post_type' => 'safari',
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
// My code here
<?php endwhile; ?>
<?php wp_pagenavi(array('before' => '', 'after' => '', 'options' => array(), 'query' => $safari_query)); ?>
<?php endif; ?>
But what i need now is, that the custom field value is displayed ONCE on top of the related posts. Something like this:
City 1:
City 2:
City 3:
and so on.
Any idea how i can add that to my existing code?
Kind regards
Edit:
With Chris' help i got it so far but it displays the city (now location) everytime:
<?php
// args
$args = array(
'post_type' => 'resort',
'meta_key' => 'wpcf-location',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
<?php
$location = get_post_meta($post->ID, 'wpcf-location', true);
$resort = the_title();
$previousResort = "";
if($location !== $previousResort ) {
//output the location name and start a list, if necessary close the prvevious list
if($current_row !==1) {
echo "</ul>";
}
echo "$location <br> <ul><li>$resort</li>";
} else {
// not a changed location, just output the resort
echo "<li>$resort</li>";
}
//finally, if this is the last row, close the list
if($current_row == $row_count) {
echo "</ul>";
}
?>
<?php endwhile; ?>
<?php endif; ?>
Final Edit:
Got it working with the help of Chris! Thanks!
<?php
// args
$args = array(
'post_type' => 'resort',
'meta_key' => 'wpcf-location',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$previousLocation = "";
$safari_query= new WP_Query( $args ); ?>
<?php if ($safari_query->have_posts()) : ?>
<?php while ($safari_query->have_posts()) : $safari_query->the_post(); ?>
<?php
$location = get_post_meta($post->ID, 'wpcf-location', true);
if($location !== $previousLocation ) {
//output the location name and the first resort.
} else {
// not a changed location, just output the resort
}
$previousLocation = $location; ?>
<?php endwhile; ?>
<?php endif; ?>