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
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 ?>