
Excluding/Removing Specific Tags in WordPress
Excluding specific tags from the tag list with the_tag seemed challenging. However, I figured out a way using get_the_tags, and I wanted to share it with you. Additionally, I noticed a previous blog post that quoted an article about wanting to exclude multiple specific tags on the IT engineer-focused Q&A site, Teratail. So, I’ve modified the code to handle multiple tags using arrays.
<?php $exclude_tags = array("tag1", "tag2", "tag3"); // Array of tags to be excluded by their slugs $tags = get_the_tags($post->ID); $separator = ', '; $output = ''; if ($tags) { foreach ($tags as $tag) { if (!in_array($tag->slug, $exclude_tags)) { // If the tag slug is not included in the excluded tags $output .= '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>' . $separator; } } echo trim($output, $separator); } ?>
On the other hand, if you want to display a list of tags in a select box and need to exclude/remove specific tags, you can use code like the following:
<?php $excluded_tag = array('tag1', 'tag2', 'tag3'); // Array of tags to be excluded by their slugs $tags = get_tags(); $filtered_tags = array(); if ($tags) { foreach ($tags as $tag) { if (!in_array($tag->slug, $excluded_tag)) { $filtered_tags[] = $tag; } } } if (!empty($filtered_tags)) : ?> <select onchange="document.location.href=this.options[this.selectedIndex].value;" class="custom-select form-control-sm"> <?php foreach ($filtered_tags as $tag) : ?> <option value="<?php echo esc_url(get_tag_link($tag->term_id)); ?>"><?php echo esc_html($tag->name); ?></option> <?php endforeach; ?> </select> <?php endif; ?>