Stop Duplicating Terms in a Foreach Loop

I have a foreach loop that prints out custom posts which uses a custom taxonomy. The user can then add whatever term/s they like to each post.
This then prints out a list of terms on the custom template page; and links them all to a filter.

My issue is that when two posts contain the same term; it outputs/prints the term out twice. How can I solve this?

Here is a temporary example: http://website-test-lab.com/sites/zuludawn/video-archive/

Here is my full page template code:

<?php
// WP_Query arguments
$args = array (
    'post_type'          => 'cpt-video-arc',
    'posts_per_page' => '-1'
);

// The Query
$query = new WP_Query( $args );
?>

<div class="entry-content units-row group">

    <div class="category-list category-list-video-archive">
                Filter by tags:
                <button class="filter" data-filter="all">Show All</button>

                <?php $terms = array(); ?>

                <?php while ( $query->have_posts() ) : $query->the_post(); ?>

                    <?php $terms_tags = wp_get_post_terms( $query->post->ID, array( 'video-arc-tags-taxonomy' ) ); ?>

                    <?php foreach ( $terms_tags as $term_tag ) { ?>
                        <?php $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.'">'.$term_tag->name.'</button>'; ?>
                        <?php echo implode($terms,' '); ?>
                    <?php } ?>

                <?php endwhile; ?>

    </div><!-- .category-list -->

</div><!-- .entry-content -->

<?php wp_reset_postdata(); ?>

2 Answers
2

I would tend to do this:

$terms = array();
$terms_tags = wp_get_post_terms( $query->post->ID, array( 'post_tag' ) ); 
foreach ( $terms_tags as $term_tag ) {
  $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.',">'.$term_tag->name.'</button>';
}
echo implode($terms,', ');

It leverages the fact that PHP does not allow duplicate array keys, and thus avoids the overhead of function calls.

In your case, it should look like this (without all of that PHP tag spam):

$query = new WP_Query( $args ); ?>
<div class="entry-content units-row group">
  <div class="category-list category-list-video-archive">
    Filter by tags:
    <button class="filter" data-filter="all">Show All</button><?php 
    $terms = array(); 
    while ( $query->have_posts() ) : 
      $query->the_post();
      $terms_tags = wp_get_post_terms( $query->post->ID, array( 'video-arc-tags-taxonomy' ) );
      foreach ( $terms_tags as $term_tag ) { 
        $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.'">'.$term_tag->name.'</button>';  
      }
    endwhile; 
    echo implode($terms,' '); // this goes outside the while loop ?>
  </div><!-- .category-list -->
</div><!-- .entry-content -->

Leave a Comment