Using WordPress ‘the_tags’ PHP filter

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

Usage

add_filter('the_tags', 'your_function_name', 10, 5);
function your_function_name($tag_list, $before, $sep, $after, $post_id) {
    // your custom code here
    return $tag_list;
}

Parameters

  • $tag_list string – List of tags.
  • $before string – String to use before the tags.
  • $sep string – String to use between the tags.
  • $after string – String to use after the tags.
  • $post_id int – Post ID.

Returns

This filter returns a modified list of tags as a string.

More information

See WordPress Developer Resources: the_tags

Examples

Add a custom class to the tags

This example adds a custom CSS class to each tag.

add_filter('the_tags', 'add_custom_class_to_tags', 10, 5);
function add_custom_class_to_tags($tag_list, $before, $sep, $after, $post_id) {
    return str_replace('<a href=', '<a class="custom-class" href=', $tag_list);
}

Add an icon before each tag

This example adds a tag icon before each tag.

add_filter('the_tags', 'add_icon_before_tags', 10, 5);
function add_icon_before_tags($tag_list, $before, $sep, $after, $post_id) {
    return str_replace($before, $before . '<i class="icon-tag"></i> ', $tag_list);
}

Wrap each tag in a <span> element

This example wraps each tag in a <span> element.

add_filter('the_tags', 'wrap_tags_in_span', 10, 5);
function wrap_tags_in_span($tag_list, $before, $sep, $after, $post_id) {
    return str_replace('<a href=', '<span><a href=', str_replace('</a>', '</a></span>', $tag_list));
}

Change the separator between tags

This example changes the separator between tags to a comma and space.

add_filter('the_tags', 'change_tags_separator', 10, 5);
function change_tags_separator($tag_list, $before, $sep, $after, $post_id) {
    return str_replace($sep, ', ', $tag_list);
}

Remove tags from a specific post ID

This example removes all tags from a specific post by its ID.

add_filter('the_tags', 'remove_tags_from_specific_post', 10, 5);
function remove_tags_from_specific_post($tag_list, $before, $sep, $after, $post_id) {
    if ($post_id === 123) {
        return '';
    }
    return $tag_list;
}