Skip to main content
1 of 3
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209

I'm not sure why do you add tags to posts that you just want to remove again in get_the_tags, but anyway, the best to option to exclude tags is to catch the array early and to remove the unneseccary before the array is returned. get_the_tags() uses get_the_terms() which is filterable through the get_the_terms.

So we can try the following:

add_filter( 'get_the_terms', function ( $terms, $post_id, $taxonomy )
{
    // Make sure we target only the post_tag taxonomy
    if ( 'post_tag' !== $taxonomy )
        return $terms;

    // Create an array of tags you want to INCLUDE, use tag id's, or slugs or names
    $tags_to_include = [ 1, 2, 3]; // using ID's
    //$tags_to_include = ['slug-1', 'slug-2', 'slug-3']; // using slugs
    //$tags_to_include = ['Name 1', 'Name 2', 'Name 3']; // using names

    // Now we can loop through our tags and exclude the one not in our included array
    foreach ( $terms as $key=>$term ) {
        // Skip tags that appear in the included list
        if ( in_array( $term->term_id, $tags_to_include ) ) // Change term_id to name or slug to match $tags_to_include
            continue;

        // Now we simply unset the tag if we reach this point
        unset( $terms[$key] );
    } // endforeach

    // return the array of tags
    return $terms;
}, 10, 3 );

Just note, this needs a bit of overheads to run, so I would still exclude the tags or not assign them when I create the posts

A final note, always, where possible, pass the complete tag object to get_tag_link(). It saves a lot on db calls and time. If you only pass the tag ID, get_tag_link() queries the db to get the complete tag object, which you already have, so

get_tag_link($this_tag->term_id)

should become

get_tag_link($this_tag)
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209