Quantcast
Channel: WordPress.org Forums » All Topics
Viewing all articles
Browse latest Browse all 59525

Need help removing duplicated results from a foreach loop

$
0
0

Replies: 0

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;

}

Viewing all articles
Browse latest Browse all 59525

Trending Articles