functions - How to get tags and categories?

admin2025-01-07  6

I used the following code to get tags from the post and then simply echo them:

$posttags = get_the_tags($post->ID);
if ($posttags) {
  foreach($posttags as $tag) { 
    echo $tag->name . ', ';}
}

Now I need to get the categories as well. My first idea was to simply duplicate the function but isn't there a way to create one single function that'll retrieve both the tags and categories and then have it echo?

I used the following code to get tags from the post and then simply echo them:

$posttags = get_the_tags($post->ID);
if ($posttags) {
  foreach($posttags as $tag) { 
    echo $tag->name . ', ';}
}

Now I need to get the categories as well. My first idea was to simply duplicate the function but isn't there a way to create one single function that'll retrieve both the tags and categories and then have it echo?

Share Improve this question edited Nov 19, 2013 at 15:19 brasofilo 22.1k8 gold badges69 silver badges264 bronze badges asked Nov 19, 2013 at 14:38 LiwiiLiwii 13 bronze badges 5
  • Well, there is get_categories() you could use maybe you can make a function and combine the two to return what you need. – Howdy_McGee Commented Nov 19, 2013 at 14:52
  • wp_get_post_terms( $post_id, $taxonomy, $args ) might help to get both tags and categories? – sri Commented Nov 19, 2013 at 14:55
  • @sri Why not answer the question and grab some reputation. – Mayeenul Islam Commented Nov 19, 2013 at 15:20
  • 1 I'm pretty sure, You should rather use get_the_terms. It runs filters and uses cache, while wp_get_post_terms is more internal method. – Krzysiek Dróżdż Commented Nov 19, 2013 at 15:52
  • @MayeenulIslam we had a better answer, may be? – sri Commented Nov 19, 2013 at 15:58
Add a comment  | 

1 Answer 1

Reset to default 0

get_the_terms( $id, $taxonomy ); is what you're looking for, I guess.

You can pass array as $taxonomy param. So this snippet:

$posttags = get_the_terms($post->ID, array('category', 'post_tag'));

should do exactly what you're trying to achieve.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736258533a519.html

最新回复(0)