4

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?

2 Answers 2

11

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.

3
  • Thanks, I did not realize the difference.
    – WalterV
    Mar 12, 2016 at 16:51
  • Always remember the naming convention of WordPress for template tags. the which mean to print get which mean to return WordPress does not always follow these. Template tags does not always use the the and get prefixes Mar 12, 2016 at 18:01
  • I was thinking about that my statement is not 100% true. Edited it :)
    – Sumit
    Mar 12, 2016 at 18:05
0

Also you can declare a variable.

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

foreach ( $taxonomy as $tax ) {
   echo esc_html( $tax->name ); 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.