Need help removing duplicated results from a foreach loop
-
I’m trying to add some sidebar content to my WordPress search results page where the top categories and tags, related to the current search query, are displayed. I have been able to generate the content, but there are a massive amount of duplicates also displaying. Click for my example page.
I’ve tried two ways of doing this, both with no success. Both were pulled from previous threads with similar questions. I would prefer avoiding 3rd party plugins if possible. Any ideas would be appreciated. Thanks
First Try:
function list_search_cats() { // Start the Loop $uniqueCats = array(); while ( have_posts() ) : the_post(); $cats = get_the_category(); if (! in_array($cats, $uniqueCats)) : $uniqueCats[] = $cats; foreach($cats as $cat) : echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>'; endforeach; endif; endwhile; }
Second Try:
function list_search_cats() { // Start the Loop $uniqueCats = array(); while ( have_posts() ) : the_post(); $cats = get_the_category(); $cats = array_unique($cats, SORT_REGULAR); foreach($cats as $cat) : echo '<li><a class="tag" href="'.get_category_link($cat->cat_ID).'">' . $cat->cat_name . '</a></li>'; endforeach; endwhile; }
The page I need help with: [log in to see the link]
Viewing 9 replies - 1 through 9 (of 9 total)
Viewing 9 replies - 1 through 9 (of 9 total)
- The topic ‘Need help removing duplicated results from a foreach loop’ is closed to new replies.