最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to test if the tag list is empty for the current page?

programmeradmin4浏览0评论

I have three custom taxonomies (topic, name, simile) Currently I display the list of tags in each taxonomy for the current post at the bottom of the post. That works fine. But I would like to give each taxonomy a heading, but only if there is something displayed for that taxonomy.

I am currently doing a similar thing with custom fields. For example the further-reading field:

<?php 
    $my_furtherReading = get_post_meta( get_the_ID(), 'further-reading', true);

    if( ! empty( $my_furtherReading ) ) {
        echo '<div class="furtherReading"><h2>Further Reading:</h2>' . $my_furtherReading . '</div>';
    }
?>  

It only prints the heading if the field is not empty.

This is how I am displaying my taxonomies (topic taxonomy)

<?php
echo get_the_term_list( $post->ID, 'topic',
'', ' ', '' );
?>

Is there a function to test if the tag list is empty? If so, could someone be kind enough to show me how to use it?

I have three custom taxonomies (topic, name, simile) Currently I display the list of tags in each taxonomy for the current post at the bottom of the post. That works fine. But I would like to give each taxonomy a heading, but only if there is something displayed for that taxonomy.

I am currently doing a similar thing with custom fields. For example the further-reading field:

<?php 
    $my_furtherReading = get_post_meta( get_the_ID(), 'further-reading', true);

    if( ! empty( $my_furtherReading ) ) {
        echo '<div class="furtherReading"><h2>Further Reading:</h2>' . $my_furtherReading . '</div>';
    }
?>  

It only prints the heading if the field is not empty.

This is how I am displaying my taxonomies (topic taxonomy)

<?php
echo get_the_term_list( $post->ID, 'topic',
'', ' ', '' );
?>

Is there a function to test if the tag list is empty? If so, could someone be kind enough to show me how to use it?

Share Improve this question asked Mar 31, 2020 at 7:52 HopefullCoderHopefullCoder 456 bronze badges 1
  • see developer.wordpress/reference/functions/get_the_term_list/… – Michael Commented Mar 31, 2020 at 17:46
Add a comment  | 

1 Answer 1

Reset to default 0

You can use wp_get_post_terms() function, like this:

if ( wp_get_post_terms( $post->ID, 'topic', [ 'fields' => 'ids' ] ) ) {
    // Your code
}

We passed the 'fields' => 'ids' in args, just to prevent instantiation of the full WP_Term objects in the background, since you only need to check if there are any, and using a different function for the HTML generation.

发布评论

评论列表(0)

  1. 暂无评论