Exclude specific tags (by id) from the_tags

Within a single post I show all tags of the specific post by using this:

the_tags( $tags_opening, ' ', $tags_ending );

But sometimes I mark a post with a tag that should not appear on that single page (but this tag shall still be found on – for example – an overview page with all tags).

How can I exclude specific tags by ID from this list of tags within the post (and just on the single page)?

2 Answers
2

Not sure that this is the best decision, but you can use the filter to cut your special tag without modifying templates.

add_filter('the_tags', 'wpse_320497_the_tags');

function wpse_320497_the_tags($tags) {
    $exclude_tag = 'word';

    // You can add your own conditions here
    // For example, exclude specific tag only for posts or custom taxonomy
    if(!is_admin() && is_singular()) {
        $tags = preg_replace("~,\s+<a[^>]+>{$exclude_tag}</a>~is", "", $tags);
    }

    return $tags;
});

If you confused with regexp, you can rewrite it with explode and strpos functions.

Hope it helps.

Leave a Comment