questions

Need to Remove Duplicate Posts in a Foreach Loop in WP code

Rate this post

I am currently looping an open position (post type) and cities in a state (position-location). The problem that I’m having is the position locations if there are more than two are duplicating the open position:

<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>    
    <?php $termsCo = get_the_terms($post->ID, 'position-location' );
    foreach ($termsCo as $termCo) :
        $locationCo = $termCo->name;
        $parentCo = $termCo->parent;
        if ($parentCo === 95) : ?><a class="ui grid segment" href="<?php echo get_permalink(); ?>">
                <div class="twelve wide column"><?php echo the_title(); ?></div>
                <div class="four wide column"><?php foreach ($termsCo as $location) : ?>
                        <?php if ( $location->name === 'Fort Collins' || $location->name === "Western Colorado" ) : ?><span class="comma"><?php echo $location->name; ?></span><?php endif; ?>
                    <?php endforeach; wp_reset_postdata(); ?></div>
            </a><?php endif; endforeach; ?>     
        <?php endwhile; wp_reset_postdata(); ?>
    <?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>

See visual here: https://web.jub.com/open-positions/

 

✔️Solution:

You have two foreach loops (one in line 4 and one in line 13). If I understand correctly, the problem is that the first loop should only enter the if part once per post ID. Have you tried a break statement in the end of your if?
Namely line 18:

<?php break; endif; endforeach; ?>

Leave a Reply

Your email address will not be published.

Back to top button