Exclude specific tags (by id) from the_tags

admin2025-06-05  2

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

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

Share Improve this question asked Nov 28, 2018 at 18:07 user3408190user3408190
Add a comment  | 

2 Answers 2

Reset to default 1

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.

You can use get_terms() to get the terms of the post_tag taxonomy according to your needs. It offers parameters to achieve this, especially exclude or exclude_tree. All available parameters are documented at WP_Term_Query::__construct().

Then you basically recreate what the_tags() does in a custom function. To elaborate a bit, the_tags() calls get_the_tag_list() which calls get_the_term_list(). If you take a look at the documentation, source code you can easily create the same markup.

Generally speaking it might be worth considering a different approach, for example using a custom taxonomy to collect those terms you want to show on overview pages but not on single pages.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749115743a316496.html

最新回复(0)