How to add Text before my Custom Term and hide it when empty

This is my code:

    ?php
    $terms = get_the_terms( $post-ID , 'this_is_custom' );
    $links = [];
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, 'this_is_custom' );
        if( !is_wp_error( $term_link ) ) {
            $links[] = 'a href=' . $term_link . '' . $term-name . '/a';
        }
    }
    echo implode(',nbsp;', $links);
    ?

The result are:

Mango, Orange, Banana

What it wants to achieve is:

Tag: Mango, Orange, Banana

How can I display the word Tag: and hide it when there is no Term inside current post?


Sorry for my English. I hope you understand.
Thanks for your answer, I really appreciated.

Topic conditional-tags template-tags tags php custom-taxonomy Wordpress

Category Web


Basically, you just need to check if the $links variable is not empty and if so, then echo the text Tag: and the $links (i.e. the terms list):

if ( ! empty( $links ) ) {
    echo 'Tags: ' . implode( ', ', $links );
}

Or a better version, check if the $terms is not a WP_Error instance and $terms is not empty:

$terms = get_the_terms( $post->ID , 'this_is_custom' );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
    $links = [];
    foreach ( $terms as $term ) {
        // ... your code.
    }
    echo 'Tags: ' . implode( ', ', $links );
}

However, if all you need is to display the terms (in the custom taxonomy this_is_custom) in the form of Tags: <tag with link>, <tag with link>, ..., i.e. simple clickable links, then you could simply use the_terms():

// Replace your entire code with just:
the_terms( $post->ID, 'this_is_custom', 'Tags: ', ',&nbsp;' ); // but I would use ', ' instead of ',&nbsp;'

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.