WordPress at a glance

wp_get_post_terms() WP 2.8.0

Gets the elements of the specified taxonomy (tag, category) to which specified post is associated.

Sometimes it is better to use get_the_terms() instead of this function, because the result is cached there.

Is the basis for: wp_get_post_tags()
Works based on: wp_get_object_terms()
✈ 1 time = 0.003903s = very slow | 50000 times = 9.43s = fast PHP 7.1.2, WP 4.8

No Hooks.

Return

Array/WP_Error. Array of WP_Term objects on success or empty array if no terms were found. WP_Error object if $taxonomy doesn't exist.

Usage

wp_get_post_terms( $post_id, $taxonomy, $args );
$post_id(int)
The Post ID.
Default: 0 (ID of the global $post)
$taxonomy(string/array)
The taxonomy slug or array of slugs for which to retrieve terms.
Default: 'post_tag'
$args(array)

Term query parameters.

  • $fields (string)
    Term fields to retrieve. Can be:

    • all - get all term fields
    • names - get term names only
    • ids - get term IDS only

    Default: 'all'

As of WP 4.7, you can specify all parameters of the get_terms() function. To 4.7. the list of parameters, see the description wp_get_object_terms()

See WP_Term_Query::__construct() for all supported arguments.

Default: array()

Examples

#1 Get the tags of the post 2647. All tag fields are retrieved:

$term_list = wp_get_post_terms( 2647, 'post_tag', array('fields' => 'all') );

/*
$term_list will contain such data:

Array(
	[0] => stdClass Object(
			[term_id] => 44
			[name] => For Beginners
			[slug] => for-newbie
			[term_group] => 0
			[term_taxonomy_id] => 44
			[taxonomy] => post_tag
			[description] => 
			[parent] => 0
			[count] => 7
		)

	[1] => stdClass Object(
			[term_id] => 48
			[name] => Theory
			[slug] => theory
			[term_group] => 0
			[term_taxonomy_id] => 49
			[taxonomy] => post_tag
			[description] => 
			[parent] => 0
			[count] => 5
		)

	[2] => stdClass Object(
			[term_id] => 12
			[name] => Hacks
			[slug] => hacks
			[term_group] => 0
			[term_taxonomy_id] => 12
			[taxonomy] => post_tag
			[description] => 
			[parent] => 0
			[count] => 10
		)
)
*/

#2 The same as in the example above, but now we get only the name field:

$term_list = wp_get_post_terms( 2647, 'post_tag', array('fields' => 'names') );

/* получим:
Array(
	[0] => For Beginners
	[1] => Theory
	[2] => Hacks
)
*/

#3 The same as in the example above, but now we get only ids field:

$term_list = wp_get_post_terms( 2647, 'post_tag', array('fields' => 'ids') );

/*
Array(
	[0] => 44
	[1] => 48
	[2] => 12
)
*/

Code of wp_get_post_terms: wp-includes/post.php VER 5.0

<?php
function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
	$post_id = (int) $post_id;

	$defaults = array('fields' => 'all');
	$args = wp_parse_args( $args, $defaults );

	$tags = wp_get_object_terms($post_id, $taxonomy, $args);

	return $tags;
}

Related Functions

From category: For posts

No comments
    Hello, !     Log In . Register