Excluding/Removing Specific Tags in WordPress

Excluding/Removing Specific Tags in WordPress

BlogCategory:Web Design
Share on XShare on LINE
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; ?>

That’s it!

AEDI is a Web and Graphic Design Company in Kurashiki, Okayama

AEDI is based in Kurashiki, Okayama, and offers services such as web and development, WordPress development, multilingual website development, SEO, UI/UX design, graphic design for logos, flyers, posters, brochures, and catalogs, motion design and motion graphics, character design, and brand design and branding. Our job is not limited to merely creating websites or designing logos; we work from the perspective of brand design and branding to bring out the value of our client’s services and products and promote new value to the world.

If you are a client in Okayama, Kurashiki, or anywhere else considering website creation and design, please feel free to contact us. Let’s work together to create exciting and outstanding products!

Related Service:

Web Design

Back to Top