0

Hi I'm trying to loop through a list of tags using wordpress. The list of tags is generated through another plugin.

at present this is the code I have

    <?php foreach($entities as $entity): ?>
    <?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>
    <li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
    <?php endforeach ?>

This outputs the list of tags as follows

    tag1
    tag1
    tag2
    tag1
    tag3

this goes on with all the tags but I'm trying to remove the duplicates, I've looked into using array_unique but cant get this to work.

Thanks

Chris Martin
  • 33
  • 2
  • 10

3 Answers3

0

You need to cache the values of $entity->galdesc you already used. An approach with in_array could look like this:

<?php $tagnamesUsed = array(); ?>
<?php foreach($entities as $entity): ?>
<?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>
<?php if (!in_array($entity->galdesc, $tagnamesUsed)): ?>
<li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
<?php $tagnamesUsed[] = $entity->galdesc; ?>
<?php endif; ?>
<?php endforeach ?>
Jojo
  • 2,720
  • 1
  • 17
  • 24
0

Your array contains objects. array_unique() tries to compare your array values as strings. See the top answer here for more detail: array_unique for objects?

One way to solve this is to create an array of tags that have already been output, then check against it each time:

<?php $arrTags = array(); ?>
<?php foreach($entities as $entity): ?>
   <?php $str = str_replace(' ', '-', esc_attr($entity->galdesc)) ?>

   <?php if(in_array($str,$arrTags)){ continue; } else { $arrTags[] = $str; } ?>

   <li><a href="#" id="<?php echo $str ?>"><?php echo_safe_html(nl2br($entity->galdesc)); ?></a></li>
<?php endforeach; ?>
Community
  • 1
  • 1
jd182
  • 3,180
  • 6
  • 21
  • 30
0

Try to iterate the array of entities twice, it's not fancy but probably will work.

  1. Parse the tag title and add it to a temp array
  2. Apply the array_unique in the temp array
  3. Iterate the temp array to print the result

The code for it will be something like this:

<?php

$tmp = array();
foreach($entities as $entity) {
    $tmp[] = str_replace(' ', '-', esc_attr($entity->galdesc));
}

$uniques = array_unique($tmp);
foreach ($uniques as $entity) {
    echo $entity . '<br>';
}
Cald
  • 741
  • 2
  • 6
  • 15