WordPress get_the_tags( int $id ): Get WordPress Post Tags – WordPress Tutorial

By | May 18, 2020

WordPress get_the_tags() function can allow us to get all tags of a post. We can control these tags by our needs. In this tutorial, we will introduce how to use this function.

Syntax

get_the_tags( int $id )

Get all tags of a post.

$id: the post id.

If this function is used in main loop. the $id is not need, otherwise, you should assign a post id.

How to use get_the_tags()?

We can use code below to get all tags of a post.

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

Where $posttags is an array, which contains some WP_Term Object object. For example:

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 108
            [name] => tag-1
            [slug] => tag-1
            [term_group] => 0
            [term_taxonomy_id] => 109
            [taxonomy] => post_tag
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [object_id] => 24
        )

    [1] => WP_Term Object
        (
            [term_id] => 109
            [name] => tag-2
            [slug] => tag-2
            [term_group] => 0
            [term_taxonomy_id] => 110
            [taxonomy] => post_tag
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [object_id] => 24
        )

)

Then we can use these WP_Term Object in our wordpress site.

Leave a Reply

Your email address will not be published. Required fields are marked *