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(', ', $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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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: ', ', ' ); // but I would use ', ' instead of ', '
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0