Jeff Sydor
Jeff Sydor

Reputation: 317

How to remove 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

Method #1:

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;

}

Method #2:

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;

}

Upvotes: 1

Views: 474

Answers (1)

DubVader
DubVader

Reputation: 1072

It looks to me like you're just missing the actual check of each category. You may need an extra foreach loop to check for dupes, then use that unique array in another foreach to display the categories. Try this:

function list_search_cats() {
  // Array to put unique cats in
  $uniqueCats = array();

  while ( have_posts() ) : the_post();

    $cats[] = get_the_category();


   // first foreach to check each cat and put in to new array 

    foreach($cats as $cat) {

      if(!in_array($cat, $uniqueCats)) {
         $uniqueCats[] = $cat;
      }

    }

   // second foreach to display the list

    foreach($uniqueCats as $cat_li) {

     $term = get_term_by('name', $cat_li, 'category');

      echo '<li><a class="tag" href="'.get_category_link($term->term_id)).'">' . $cat_li . '</a></li>';

    }

  endwhile;

}

Upvotes: 0

Related Questions