admin管理员组

文章数量:1319479

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 ); 
}

本文标签: termsCorrect use of gettheterms()