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.
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. Share Improve this question asked Jan 16, 2021 at 3:37 TaufanTaufan 32 bronze badges 2 |
1 Answer
Reset to default 0Basically, 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 ', '
the_tags();
to show tags and it will show "Tags: Mango, Orange, Banana". – Tiyo Commented Jan 16, 2021 at 9:21the_tags( 'Tags: ', ', ' );
and yes, when the there is no tag in your post, there will be nothing. no "Tags:" text. – Tiyo Commented Jan 16, 2021 at 9:24