WordPress at a glance

wp_get_post_tags() WP 2.3.0

Gets a list of tags for a specified post as an array.

This is the wrapper for wp_get_post_terms().

Works based on: wp_get_post_terms()
✈ 1 time = 0.016552s = extreme slow | 50000 times = 16.89s = slow PHP 7.2.5, WP 4.9.8

No Hooks.

Return

Array/WP_Error.

  • array( WP_Term, WP_Term ) — Array of WP_Term objects.
  • array() — empty array if no tags were found.
  • WP_Error — WP_Error object if 'post_tag' taxonomy doesn't exist.

Usage

wp_get_post_tags( $post_id, $args );
$post_id(int)
The Post ID. Does not default to the ID of the global $post.
Default: 0
$args(array)
Tag query parameters. See WP_Term_Query::__construct() for supported arguments.
Default: empty array

Examples

#1 Get the tags of the current post

Let's say the post has the following tags: tag2, tag5, tag6, then:

$tags = wp_get_post_tags( $post->ID );
print_r( $tags );

/*
As a result, we get the following code on the screen:

Array (
   [0] => stdClass Object (
		   [term_id] => 4
		   [name] => tag2
		   [slug] => tag2
		   [term_group] => 0
		   [term_taxonomy_id] => 4
		   [taxonomy] => post_tag
		   [description] => 
		   [parent] => 0
		   [count] => 7
	   )

   [1] => stdClass Object (
		   [term_id] => 7
		   [name] => tag5
		   [slug] => tag5
		   [term_group] => 0
		   [term_taxonomy_id] => 7
		   [taxonomy] => post_tag
		   [description] => 
		   [parent] => 0
		   [count] => 6
	   )

   [2] => stdClass Object (
		   [term_id] => 16
		   [name] => tag6
		   [slug] => tag6
		   [term_group] => 0
		   [term_taxonomy_id] => 16
		   [taxonomy] => post_tag
		   [description] => 
		   [parent] => 0
		   [count] => 2
	   )
)
*/

#2 Get a list of tags IDs of the current post

The list will contain only tags IDS (id field):

global $post;
$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
// $tag_ids = [ 4, 7, 16 ]

Code of wp_get_post_tags: wp-includes/post.php VER 5.0.1

<?php
function wp_get_post_tags( $post_id = 0, $args = array() ) {
	return wp_get_post_terms( $post_id, 'post_tag', $args);
}

Related Functions

From category: For posts

No comments
    Hello, !     Log In . Register