Reputation: 2711
I'm creating a property page and there is a section where it lists in what areas there are properties. I have the areas stored in the backend inside a advanced custom field(Town) on a custom post type. Now when I loop through each property getting the value and display it in a list I get multiple of the same value as some of the properties share the same Town.
So what I want to be able to do is loop through the properties getting each properties Town custom field value and store it in an array. But if the array already holds the same value I don't want to store it. Then I want to display the array as a list.
for example; we start looping through the properties storing the Town custom field value in an array. But before we store it we check if that value already exists inside the array, if it does we don't store it. Once the loop has finished we echo the array as a list.
this is what I have so far;
<?php
$args = array(
'post_type' => 'property',
'posts_per_page' => -1,
'meta_key' => 'property_status',
'meta_value' => 'For Sale'
);
$query = new WP_Query($args);
?>
<?php if( $query->have_posts() ): ?>
<ul>
<?php while( $query->have_posts() ): $query->the_post(); ?>
<li><?php get_field('town'); ?></li>
<?php endwhile; ?>
</ul>
<?php wp_reset_query(); ?>
<?php endif; ?>
Upvotes: 0
Views: 2268
Reputation: 1475
This is the way you will get unique towns of properties.
<?php
$args = array(
'post_type' => 'property',
'posts_per_page' => -1,
'meta_key' => 'property_status',
'meta_value' => 'For Sale'
);
$query = new WP_Query($args);
?>
<?php if( $query->have_posts() ): ?>
<ul>
<?php while( $query->have_posts() ): $query->the_post();
$town_array[] = get_field('town'); ?>
<li><?php get_field('town'); ?></li>
<?php endwhile; ?>
</ul>
<?php wp_reset_query(); ?>
<?php endif; ?>
<?php $towns = array_unique($town_array);
print_r($towns) ?>
Upvotes: 2