Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

So the title is confusing but I can't think of a better way to word it. Basically, I have two taxonomies of "state" and "city" (that have to stay separate for other reasons). Lets say for instance, a term in the taxonomy of "state" is "Connecticut" I then want to display a list of terms from the taxonomy of "city" that populate only from posts with the "state" term as "Connecticut". Basically, I want to dynamically call the state and display the cities in the sidebar on the archive page... I know, this sounds really confusing.

This code works but obviously causes duplicates, I would like each one only listed once.

<?php
$pterms = get_the_terms( $post->ID, 'property_location' );

if ( $pterms && ! is_wp_error( $pterms ) ) : 

$prop_links = array();

foreach ( $pterms as $el_term ) {
    $prop_links[] = $el_term->name;
}

$st_location = join( ", ", $prop_links );   
?>
<?php endif; ?>
<?php endwhile; ?>

<!-- this is a separate loop -->

<?php
$args = array(
 'post_type' => 'property',
 'post_status' => 'publish',
 'posts_per_page' => -1,
 'property_location' => ''.$st_location.''
);
$the_query = new WP_Query( $args ); ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>

<p><?php echo get_the_term_list( $post->ID, 'city', '', '', '' ); ?></p> 

<?php endwhile; ?>

Any suggestions?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Your approach isn't bad, but instead of echoing all of these out, you should store them in an array, then use array_unique to remove duplicate entries before displaying.

<?php 
$array_out = array();
while ($the_query->have_posts()) : $the_query->the_post(); ?>
    $terms = get_the_terms( $post->ID, 'city'); 
    foreach($terms as $term){
        $term_link = get_term_link($term, 'city');
        $array_out[] = '<a href="'.$term_link.'">'.$term->name.'</a>';
    }
endwhile; 

$array_clean = array_unique($array_out);
echo '<p>' . implode('</p><p>', $array_clean) . '</p>';

We have to build the link ourselves using get_term_link() so the array holds each term separately, not by group as it is related to each post.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.