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

terms - Correct use of get_the_terms()

programmeradmin1浏览0评论

I need to print all terms associated to a custom post type post. In the post template I wrote that code:

<?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?>
     <?php echo $cat->name; ?>
<?php endforeach; ?>

The loop works correctly, but before the list also the id was printed. Like:

37
taxonomy01
taxonomy02
taxonomy03

What is wrong?

I need to print all terms associated to a custom post type post. In the post template I wrote that code:

<?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?>
     <?php echo $cat->name; ?>
<?php endforeach; ?>

The loop works correctly, but before the list also the id was printed. Like:

37
taxonomy01
taxonomy02
taxonomy03

What is wrong?

Share Improve this question edited Mar 13, 2016 at 21:04 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Mar 12, 2016 at 16:36 wavwav 1971 gold badge1 silver badge6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

the_ID() print the post ID. You need to use the get_the_ID() which return the post ID.

Example:

foreach (get_the_terms(get_the_ID(), 'taxonomy') as $cat) {
   echo $cat->name;
}

Always remember the naming convention of WordPress for template tags. the which mean to print get which mean to return in most of the cases.

Also you can declare a variable.

$taxonomy = get_the_terms( get_the_ID(), 'taxonomy' );

foreach ( $taxonomy as $tax ) {
   echo esc_html( $tax->name ); 
}
发布评论

评论列表(0)

  1. 暂无评论