wp_get_object_terms()
云策文档标注
概述
wp_get_object_terms() 函数用于检索与指定对象(如文章)关联的分类法术语,支持多个对象和分类法。它直接查询数据库,结果未缓存,可能影响性能。
关键要点
- 参数:$object_ids(对象ID,必需,整数或数组)、$taxonomies(分类法名称,必需,字符串或数组)、$args(可选参数数组,参考 WP_Term_Query)。
- 返回值:返回 WP_Term 数组、整数数组、字符串数组、计数字符串或 WP_Error(如果分类法不存在)。
- 性能注意:结果未缓存,每次调用都会进行数据库查询;建议在可能时使用 get_the_terms() 以提高性能。
- 内部实现:基于 WP_Term_Query,支持过滤钩子如 wp_get_object_terms_args 和 get_object_terms。
- 版本变化:从 4.7.0 开始重构使用 WP_Term_Query,6.3.0 默认 update_term_meta_cache 为 false。
代码示例
$product_terms = wp_get_object_terms( $post->ID, 'product' );
if ( ! empty( $product_terms ) ) {
if ( ! is_wp_error( $product_terms ) ) {
echo '<ul>';
foreach( $product_terms as $term ) {
echo '<li><a href="' . esc_url( get_term_link( $term->slug, 'product' ) ) . '">' . esc_html( $term->name ) . '</a></li>';
}
echo '</ul>';
}
}注意事项
- 确保分类法存在,否则返回 WP_Error。
- 在循环中频繁调用可能导致性能问题,优先考虑缓存函数如 get_the_terms()。
- 参数 $args 可以传递 WP_Term_Query 支持的选项,如 fields、orderby 等。
原文内容
Retrieves the terms associated with the given object(s), in the supplied taxonomies.
Parameters
$object_idsint|int[]required-
The ID(s) of the object(s) to retrieve.
$taxonomiesstring|string[]required-
The taxonomy names to retrieve terms from.
$argsarray|stringoptional-
See WP_Term_Query::__construct() for supported arguments.
Default:
array()
Source
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 <a href="https://developer.wordpress.org/reference/functions/wp_get_object_terms/">wp_get_object_terms()</a> 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
* '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 );
}
Hooks
- apply_filters( ‘get_object_terms’, WP_Term[]|int[]|string[]|string $terms, int[] $object_ids, string[] $taxonomies, array $args )
-
Filters the terms for a given object or objects.
- apply_filters( ‘wp_get_object_terms’, WP_Term[]|int[]|string[]|string $terms, string $object_ids, string $taxonomies, array $args )
-
Filters the terms for a given object or objects.
- apply_filters( ‘wp_get_object_terms_args’, array $args, int[] $object_ids, string[] $taxonomies )
-
Filters arguments for retrieving object terms.
Changelog
| Version | Description |
|---|---|
| 6.3.0 | Passing update_term_meta_cache argument value false by default resulting in get_terms() to not prime the term meta cache. |
| 4.7.0 | Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments. |
| 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. |
| 4.2.0 | Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of $orderby.Introduced $parent argument. |
| 2.3.0 | Introduced. |
Skip to note 4 content
Felipe Lavín
It’s very important to note that if you wish to get the taxonomy terms for a given post, your first choice should be using get_the_terms() since it uses the WordPress object cache and can potentialy save a lot of extra queries.
This is specially useful if you’re looping over posts results, because WP_Query by default loads all the terms for the queried posts.
Skip to note 5 content
Codex
Example
Returns a list of all ‘product’ taxonomy terms that are applied to $post:
$product_terms = wp_get_object_terms( $post->ID, 'product' ); if ( ! empty( $product_terms ) ) { if ( ! is_wp_error( $product_terms ) ) { echo '<ul>'; foreach( $product_terms as $term ) { echo '<li><a href="' . esc_url( get_term_link( $term->slug, 'product' ) ) . '">' . esc_html( $term->name ) . '</a></li>'; } echo '</ul>'; } }Skip to note 6 content
Kamal Hosen
Example of related EDD products
$exclude_post_id = $post->ID; $taxchoice = 'download_tag'; $custom_taxterms = wp_get_object_terms( $post->ID, $taxchoice, array('fields' => 'ids') ); $arguments = array( 'post_type' => 'download', 'post_status' => 'publish', 'posts_per_page' => 3, 'orderby' => 'rand', 'ignore_sticky_posts' => 1, 'post__not_in' => array($post->ID, '81099'), 'ignore_sticky_posts'=>1, 'tax_query' => array( array( 'taxonomy' => $taxchoice, 'field' => 'id', 'terms' => $custom_taxterms ) ), ); $post_query = new WP_Query($arguments);