Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get WordPress tags from a certain post by its ID?

I've searched all over the place and scoured the API. All I'm coming up with are ways to get POSTS by a TAG, but not get the TAGS of a SPECIFIC post by its ID.

What I'm trying to do is pretty simple - I have a post and I want to check if it has a specific tag - 'specialtag' - and then do something on that page if it has this tag. Nothing seems to point me in the right direction. Is there something I'm not seeing?

like image 682
Thirk Avatar asked Sep 02 '25 02:09

Thirk


1 Answers

It's simple, you can use get_the_tags function like this :

CODEX: The function return an array of objects, one object for each tag assigned to the post.

Example 1:

If you have the post ID you can retrieve the tag associated with the post by this code

$postid = $post->ID; 
get_the_tags($postid);

Example 2:

retrieve the tag associated with the post inside the loop

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

this function is used in The Loop, then no ID need be passed

Example 3:

retrieve the tag associated with the post outside the loop

global $post;
   foreach(get_the_tags($post->ID) as $tag) {
      echo $tag->name . ', ';
   }
like image 54
dardar.moh Avatar answered Sep 05 '25 01:09

dardar.moh