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.
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.
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 );
strcasecmp
function php.net/manual/en/function.strcasecmp.php
Commented
Apr 13, 2012 at 4:48
This is a snippet from one of my blogs:
function get_filtered_tags($post_id) {
// the slugs to be INCLUDED in the term list:
$primary_tags = array( 'books', 'travel', ... );
$post_tags = wp_get_object_terms($post_id, 'post_tag');
if( ! empty( $post_tags ) ) {
if( ! is_wp_error( $post_tags )) {
$tag_end = __( ', ', 'twentytwelve' );
foreach ( $post_tags as $term ) {
$term_slug = $term->slug;
if ( in_array( $term_slug, $primary_tags) ) {
if ( isset( $tag_list ) ) {
$tag_list .= $tag_end;
}
$tag_list .= '<a href="' . get_term_link($term_slug, 'post_tag') .
'">' . $term->name . '</a>';
}
}
}
}
return $tag_list;
}
If you want to exclude $primary_tags
do the following instead:
if ( ! in_array( $term_slug, $primary_tags) ) {
...
}
I.e. add a !
before in_array( ... )
.
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;
}
'get_the_terms'
, it will have effect on different other functions, which use get_the_terms
internally. By doing it you exclude tags "globally".
Commented
Apr 12, 2012 at 7:53