Skip to content
Advertisement

How to prevent duplicate results in For Each loop?

I am using a foreach loop to look at custom taxonomies associated with my custom post type. The issue I am having is that I am getting multiple buttons to display for posts that have more than one tax term selected.

What I would like to have happen is the loop search for one or more of the “age/grades” and then display a single button with the correct text and link. However, I am getting one button for each grade selected for the program (e.g. a Grade 3-6 program has four buttons: one for each applicable grade).

Any idea on how to prevent the duplicates?

Here is my current code:

JavaScript

Advertisement

Answer

Use separate foreach loops and break when it’s found.

Your || is also not working how you want it to. You should use in_array which correctly compares the same value to many others:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement