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?

Related posts

Leave a Reply

3 comments

  1. 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 . ', ';
       }
    
  2. If you need to get tags by post id you could use the followng function. This will work on anywhere since the method is based on database querying.

    function sc_tf_get_tags_as_array($post_id){
        global $wpdb;
        $tbl_terms = $wpdb->prefix . "terms";
        $tbl_term_relationships = $wpdb->prefix . "term_relationships";
    
        $sql = "SELECT name FROM $tbl_terms WHERE term_id in (SELECT term_taxonomy_id FROM $tbl_term_relationships WHERE object_id='$post_id');";
        $results = $wpdb->get_results($sql);
    
        if($results){
            foreach($results as $row){
                $tags_list[] = $row->name;
            }
        }
    
        return $tags_list;
    }