Using WordPress ‘get_the_tags’ PHP filter

The get_the_tags WordPress PHP filter allows you to modify the array of tags for a given post.

Usage

add_filter('get_the_tags', 'your_function_name', 10, 1);
function your_function_name($terms) {
    // your custom code here
    return $terms;
}

Parameters

  • $terms (array|false|WP_Error): Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.

More information

See WordPress Developer Resources: get_the_tags

Examples

Remove specific tags

Remove specific tags from the post tags array.

add_filter('get_the_tags', 'remove_specific_tags', 10, 1);
function remove_specific_tags($terms) {
    if (is_array($terms)) {
        $terms = array_filter($terms, function ($term) {
            // Remove tags with the slug 'example-tag' and 'another-tag'
            return !in_array($term->slug, array('example-tag', 'another-tag'));
        });
    }
    return $terms;
}

Add a custom class to the tag links.

add_filter('get_the_tags', 'add_custom_class_to_tag_links', 10, 1);
function add_custom_class_to_tag_links($terms) {
    if (is_array($terms)) {
        foreach ($terms as $term) {
            // Add a custom class to the tag link
            $term->link = str_replace('<a href=', '<a class="custom-class" href=', $term->link);
        }
    }
    return $terms;
}

Change the URLs for the tag links.

add_filter('get_the_tags', 'change_tag_link_urls', 10, 1);
function change_tag_link_urls($terms) {
    if (is_array($terms)) {
        foreach ($terms as $term) {
            // Change the tag link URL to an external website
            $term->link = str_replace(get_term_link($term), 'https://externalwebsite.com/tags/' . $term->slug, $term->link);
        }
    }
    return $terms;
}

Sort tags alphabetically

Sort the tags alphabetically.

add_filter('get_the_tags', 'sort_tags_alphabetically', 10, 1);
function sort_tags_alphabetically($terms) {
    if (is_array($terms)) {
        usort($terms, function ($a, $b) {
            return strcmp($a->name, $b->name);
        });
    }
    return $terms;
}

Capitalize tag names

Capitalize the first letter of each tag name.

add_filter('get_the_tags', 'capitalize_tag_names', 10, 1);
function capitalize_tag_names($terms) {
    if (is_array($terms)) {
        foreach ($terms as $term) {
            // Capitalize the tag name
            $term->name = ucfirst($term->name);
        }
    }
    return $terms;
}