Using WordPress ‘get_tags’ PHP filter

The get_tags WordPress PHP filter allows you to modify the array of term objects returned for the ‘post_tag’ taxonomy.

Usage

add_filter('get_tags', 'your_custom_function', 10, 2);
function your_custom_function($tags, $args) {
    // your custom code here
    return $tags;
}

Parameters

  • $tags (WP_Term[]|int|WP_Error): Array of ‘post_tag’ term objects, a count thereof, or WP_Error if any of the taxonomies do not exist.
  • $args (array): An array of arguments. See get_terms() for more information.

More information

See WordPress Developer Resources: get_tags

Examples

Remove specific tags

Remove tags with IDs 3 and 5 from the list of tags.

add_filter('get_tags', 'remove_specific_tags', 10, 2);
function remove_specific_tags($tags, $args) {
    $exclude_ids = array(3, 5);
    foreach ($tags as $key => $tag) {
        if (in_array($tag->term_id, $exclude_ids)) {
            unset($tags[$key]);
        }
    }
    return $tags;
}

Sort tags alphabetically

Sort the tags list alphabetically by name.

add_filter('get_tags', 'sort_tags_alphabetically', 10, 2);
function sort_tags_alphabetically($tags, $args) {
    usort($tags, function($a, $b) {
        return strcmp($a->name, $b->name);
    });
    return $tags;
}

Limit number of tags

Limit the number of displayed tags to 5.

add_filter('get_tags', 'limit_number_of_tags', 10, 2);
function limit_number_of_tags($tags, $args) {
    return array_slice($tags, 0, 5);
}

Exclude tags with low post count

Exclude tags that have less than 3 posts.

add_filter('get_tags', 'exclude_low_count_tags', 10, 2);
function exclude_low_count_tags($tags, $args) {
    foreach ($tags as $key => $tag) {
        if ($tag->count < 3) {
            unset($tags[$key]);
        }
    }
    return $tags;
}

Capitalize tag names

Capitalize the first letter of each tag name.

add_filter('get_tags', 'capitalize_tag_names', 10, 2);
function capitalize_tag_names($tags, $args) {
    foreach ($tags as $key => $tag) {
        $tag->name = ucfirst($tag->name);
    }
    return $tags;
}