Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Does anyone know how to exclude/filter a tag from the HTML string generated by get_the_tag_list()?

http://codex.wordpress.org/Function_Reference/get_the_tag_list

Any help much appreciated.

share|improve this question

2 Answers

up vote 0 down vote accepted
function mytheme_filter_tags( $term_links ) {
    $result = array();
    $exclude_tags = array( 'some tag', 'another tag', 'third tag' );
    foreach ( $term_links as $link ) {
        foreach ( $exclude_tags as $tag ) {
            if ( stripos( $link, $tag ) !== false ) continue 2;
        }
        $result[] = $link;
    }
    return $result;
}
add_filter( "term_links-post_tag", 'mytheme_filter_tags', 100, 1 );

// do loop stuff
echo get_the_tag_list('<p>Tags: ',', ','</p>');
// end loop stuff

remove_filter( "term_links-post_tag", 'mytheme_filter_tags', 100 );
share|improve this answer
Thanks very much Eugene. Works perfectly. Just a couple of follow up questions regarding your answer: 1. If I wanted to match the tag exactly (but case insensitive) which php string comparison function is best to use in this situation? 2. Why have you set the priority of the filters to 100? – thegonzobeat Apr 13 '12 at 0:31
#1 if I understand you correctly, you need strcasecmp function php.net/manual/en/function.strcasecmp.php – Eugene Manuilov Apr 13 '12 at 4:48
#2 I pursued two following goals: - to execute my filter function after anyone else filter - and to remove exactly my function from filters list – Eugene Manuilov Apr 13 '12 at 4:52
Thanks again Eugene. – thegonzobeat Apr 13 '12 at 8:35

get_the_tag_list calls get_the_term_list which then calls get_the_terms that has a filter named get_the_terms so you can use that filter to exclude your tags:

//add filter
add_filter( 'get_the_terms', 'exclude_terms_48735', 10, 1 );
//function to do filtering
function exclude_terms_48735( $terms ) {
    //list the unwanted terms ids
    $blacklist_terms = array( 1,2,3);
    // loop through the terms
    foreach( $terms as $k => $term ) {
        //only remove term if it's ID is in the array.
        if(in_array( $term->term_id, $blacklist_terms, true )) 
            unset( $terms[$k] );
    }
    return $terms;
}
share|improve this answer
If you add hook on filter 'get_the_terms', it will have effect on different other functions, which use get_the_terms internally. By doing it you exclude tags "globally". – Eugene Manuilov Apr 12 '12 at 7:53
Thanks very much for your help Bainternet. I went with Eugene's answer because I only wanted to change the output of get_the_tag_list in this case. – thegonzobeat Apr 13 '12 at 0:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.