0

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

1 Answer 1

2

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) ?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but nothing happens
please see my edits code as i forgot to use variable as array now i have changed $town_array to $town_array[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.