wp_get_object_terms()WP 2.3.0

Gets the terms (taxonomy elements) related to the given object(s) (posts) in the specified taxonomy.

This function is the core of the function get_the_terms(). In most cases, it is better to use get_the_terms() instead of this function, because the result is cached there and can potentially save many additional queries.

This is especially useful if you are iterating over post results in a loop, because WP_Query{} by default loads all terms for the queried posts.

Note: this function can accept multiple posts and multiple taxonomy names to get all data at once, while get_the_terms() works with a single post and a single taxonomy.

1 time — 0.003926 sec (very slow) | 50000 times — 8.64 sec (fast) | PHP 7.1.2, WP 4.8

Returns

WP_Term[]|Int[]|String[]|String|WP_Error.

  • Array of objects containing information about the terms. On error, it will return a WP_Error object.
  • array() - if no elements are found.
  • WP_Error - if the specified taxonomy does not exist.

Usage

wp_get_object_terms( $object_ids, $taxonomies, $args );
$object_ids(string/array) (required)
ID of the objects whose terms need to be retrieved. More than one ID should be specified in an array: array(23, 56, 89).
$taxonomies(string/array) (required)
The name of the taxonomy whose terms need to be retrieved. Multiple names can be specified. Multiple names should be passed in an array: array('category', 'name2').
$args(string/array)

Arguments according to which the result will be obtained. Can be specified as a query string.

Starting from WP 4.7, all parameters of the function get_terms() can be specified.

Default: presets

  • orderby(string)
    By which criterion to sort the result. Can be:

    • name - by name. Default.
    • count - by the number of posts.
    • slug - by slug.
    • term_group -
    • term_order -
    • none - output without sorting.

    Default: 'name'

  • order(string)
    Sorting direction. ASC — in order, DESC — in reverse order.
    Default: 'ASC'

  • fields(string)
    Which fields to include in the resulting array. Can be:

    • all - the result will be an array of objects with all information about each term.
    • ids - get only the term IDs.
    • names - get only the term names.
    • slugs - get only the term slugs.
    • all_with_object_id - the same as all, plus the term IDs.
    • tt_ids - will return the taxonomy term IDs (internal ID for table relations).

    Combined options are also possible, for example:

    • id=>name - will return a pair ID => Name.
    • id=>slug - will return a pair ID => Slug.

    Default: 'all'

  • meta_query(array)
    Meta query parameters. See WP_Meta_Query{}. Since version 4.4.

  • update_term_meta_cache(boolean)
    Whether to update the metadata cache of the retrieved taxonomy elements. Since version 4.4.
    Default: false (was true until WP 6.3)

Examples

0

#1 All elements of the 'product_categories' taxonomy post

Get the terms of the product_categories taxonomy of the current post ($post->ID):

$product_cats = wp_get_object_terms( $post->ID, 'product_categories' );
0

#2 Returns the list of elements of the "product" taxonomy that are set for the posts:

$product_terms = wp_get_object_terms( $post->ID, 'product' );

if( $product_terms && ! is_wp_error( $product_terms ) ){

	$lis = [];
	foreach( $product_terms as $term ){
		$lis[] = '<li><a href="'. get_term_link( $term ) .'">'. esc_html( $term->name ) .'</a></li>';
	}

	echo '<ul>'. implode( "\n", $lis ) .'</ul>';
}
0

#3 Gets the topmost taxonomy element for the specified or current post in the loop

See the example in the get_the_terms() description.

Changelog

Since 2.3.0 Introduced.
Since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of $orderby. Introduced $parent argument.
Since 4.4.0 Introduced $meta_query and $update_term_meta_cache arguments. When $fields is 'all' or 'all_with_object_id', an array of WP_Term objects will be returned.
Since 4.7.0 Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments.
Since 6.3.0 Passing update_term_meta_cache argument value false by default resulting in get_terms() to not prime the term meta cache.

wp_get_object_terms() code WP 6.9.1

function wp_get_object_terms( $object_ids, $taxonomies, $args = array() ) {
	if ( empty( $object_ids ) || empty( $taxonomies ) ) {
		return array();
	}

	if ( ! is_array( $taxonomies ) ) {
		$taxonomies = array( $taxonomies );
	}

	foreach ( $taxonomies as $taxonomy ) {
		if ( ! taxonomy_exists( $taxonomy ) ) {
			return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
		}
	}

	if ( ! is_array( $object_ids ) ) {
		$object_ids = array( $object_ids );
	}
	$object_ids = array_map( 'intval', $object_ids );

	$defaults = array(
		'update_term_meta_cache' => false,
	);

	$args = wp_parse_args( $args, $defaults );

	/**
	 * Filters arguments for retrieving object terms.
	 *
	 * @since 4.9.0
	 *
	 * @param array    $args       An array of arguments for retrieving terms for the given object(s).
	 *                             See {@see wp_get_object_terms()} for details.
	 * @param int[]    $object_ids Array of object IDs.
	 * @param string[] $taxonomies Array of taxonomy names to retrieve terms from.
	 */
	$args = apply_filters( 'wp_get_object_terms_args', $args, $object_ids, $taxonomies );

	/*
	 * When one or more queried taxonomies is registered with an 'args' array,
	 * those params override the `$args` passed to this function.
	 */
	$terms = array();
	if ( count( $taxonomies ) > 1 ) {
		foreach ( $taxonomies as $index => $taxonomy ) {
			$t = get_taxonomy( $taxonomy );
			if ( isset( $t->args ) && is_array( $t->args ) && array_merge( $args, $t->args ) != $args ) {
				unset( $taxonomies[ $index ] );
				$terms = array_merge( $terms, wp_get_object_terms( $object_ids, $taxonomy, array_merge( $args, $t->args ) ) );
			}
		}
	} else {
		$t = get_taxonomy( $taxonomies[0] );
		if ( isset( $t->args ) && is_array( $t->args ) ) {
			$args = array_merge( $args, $t->args );
		}
	}

	$args['taxonomy']   = $taxonomies;
	$args['object_ids'] = $object_ids;

	// Taxonomies registered without an 'args' param are handled here.
	if ( ! empty( $taxonomies ) ) {
		$terms_from_remaining_taxonomies = get_terms( $args );

		// Array keys should be preserved for values of $fields that use term_id for keys.
		if ( ! empty( $args['fields'] ) && str_starts_with( $args['fields'], 'id=>' ) ) {
			$terms = $terms + $terms_from_remaining_taxonomies;
		} else {
			$terms = array_merge( $terms, $terms_from_remaining_taxonomies );
		}
	}

	/**
	 * Filters the terms for a given object or objects.
	 *
	 * @since 4.2.0
	 *
	 * @param WP_Term[]|int[]|string[]|string $terms      Array of terms or a count thereof as a numeric string.
	 * @param int[]                           $object_ids Array of object IDs for which terms were retrieved.
	 * @param string[]                        $taxonomies Array of taxonomy names from which terms were retrieved.
	 * @param array                           $args       Array of arguments for retrieving terms for the given
	 *                                                    object(s). See wp_get_object_terms() for details.
	 */
	$terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );

	$object_ids = implode( ',', $object_ids );
	$taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";

	/**
	 * Filters the terms for a given object or objects.
	 *
	 * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
	 * {@see 'get_object_terms'} filter is recommended as an alternative.
	 *
	 * @since 2.8.0
	 *
	 * @param WP_Term[]|int[]|string[]|string $terms      Array of terms or a count thereof as a numeric string.
	 * @param string                          $object_ids Comma separated list of object IDs for which terms were retrieved.
	 * @param string                          $taxonomies SQL fragment of taxonomy names from which terms were retrieved.
	 * @param array                           $args       Array of arguments for retrieving terms for the given
	 *                                                    object(s). See wp_get_object_terms() for details.
	 */
	return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
}