1

At the bottom of a post, I show all that tags that post has.

If the current post is the only post with tag X, then I don't want tag X to show in the list. Because if someone clicks on that, they'll be taken to an archive page where the post they were just looking at is the only post listed. Useless.

Otherwise I don't have a problem with tags that only have one post.

It's a custom post type with custom taxonomies (three different taxonomies: topic, name, simile)

Here is how I am displaying the topic taxonomy:

<p class="meta-tag-list"> 
<?php
echo get_the_term_list( $post->ID, 'topic',
'', ' ', '' );
?>  </p>

Does a function already exist that would let me do this?

1
  • Thanks for accepting the answers. As a complementary notes, I think @Michael's method is also working. If using a filter, you don't have to change your template code. It just modify the terms variable before passing to get_the_term_list(). The spirit and principal in behind are same. If you have a lot of templates, then using a filter is an advantage. Mar 31, 2020 at 8:13

2 Answers 2

1

Because get_the_term_list() create the html link for you. So

  1. you need to use wp_get_object_terms to get a list of terms info first with count for handling.
  2. compare each tag count, if the count > 1 then create the link and output

I have just tried. It works

<p class="meta-tag-list"> 
<?php
$terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic'
foreach ($terms as $key => $term) {
    if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen
        $link = get_term_link( $term->term_id );
        echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
    }
}
?>  
</p>
1
  • This worked perfectly! Thanks. I like this solution since it doesn't require me to write a new function. Mar 31, 2020 at 8:05
2

you can try using a filter function (added into functions.php of your (child) theme), specific to your taxonomy 'topic': (based on https://developer.wordpress.org/reference/functions/get_the_term_list/ and https://developer.wordpress.org/reference/functions/get_the_terms/ )

// define the get_the_terms callback 
function filter_get_the_topic_terms( $terms, $postid, $taxonomy ) {
    if( !is_admin() && $taxonomy == 'topic' ) : // make filter magic happen here... 
        $filtered_terms = array();
        foreach( $terms as $term ) :
            if( $term->count > 1 ) {
                $filtered_terms[] = $term;
            }
        endforeach;
        $terms = $filtered_terms;
    endif;
    return $terms;
}
// add the filter 
add_filter( 'get_the_terms', 'filter_get_the_topic_terms', 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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