0

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.
2
  • I think you can just use the_tags(); to show tags and it will show "Tags: Mango, Orange, Banana". – Tiyo Jan 16 at 9:21
  • OR, you can use this to custom your text. the_tags( 'Tags: ', ', ' ); and yes, when the there is no tag in your post, there will be nothing. no "Tags:" text. – Tiyo Jan 16 at 9:24
0

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( ',&nbsp;', $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( ',&nbsp;', $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;'
1
  • 1
    It's work. Thanks for make my life easier 🙏🙏🙏 – Taufan Jan 17 at 4:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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