get_object_term_cache()
云策文档标注
概述
get_object_term_cache() 函数用于从缓存中检索指定对象 ID 的术语对象。它依赖于上游函数(如 get_the_terms())填充缓存,仅获取已存在的缓存数据。
关键要点
- 函数从缓存中获取术语对象,不负责填充缓存,上游函数需处理缓存初始化。
- 参数包括对象 ID(如文章、评论或用户 ID)和分类法名称,均为必需。
- 返回值可能是 WP_Term 对象数组、false(缓存为空)或 WP_Error(获取术语时出错)。
- 函数内部使用 wp_cache_get() 检索缓存,并处理向后兼容性(支持插件缓存对象而非 ID)。
- 通过 _prime_term_caches() 填充术语对象缓存,并调用 get_term() 获取术语数据。
代码示例
function get_object_term_cache( $id, $taxonomy ) {
$_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
// We leave the priming of relationship caches to upstream functions.
if ( false === $_term_ids ) {
return false;
}
// Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
$term_ids = array();
foreach ( $_term_ids as $term_id ) {
if ( is_numeric( $term_id ) ) {
$term_ids[] = (int) $term_id;
} elseif ( isset( $term_id->term_id ) ) {
$term_ids[] = (int) $term_id->term_id;
}
}
// Fill the term objects.
_prime_term_caches( $term_ids );
$terms = array();
foreach ( $term_ids as $term_id ) {
$term = get_term( $term_id, $taxonomy );
if ( is_wp_error( $term ) ) {
return $term;
}
$terms[] = $term;
}
return $terms;
}注意事项
- 函数自 WordPress 2.3.0 引入,4.7.0 版本起在术语错误时返回 WP_Error 对象。
- 相关函数包括 _prime_term_caches()、wp_cache_get()、get_term() 和 is_wp_error(),用于缓存和术语处理。
- 被多个函数使用,如 get_terms_to_edit()、get_the_terms() 和 is_object_in_term(),涉及后台管理和前端显示。
原文内容
Retrieves the cached term objects for the given object ID.
Description
Upstream functions (like get_the_terms() and is_object_in_term() ) are responsible for populating the object-term relationship cache. The current function only fetches relationship data that is already in the cache.
Parameters
$idintrequired-
Term object ID, for example a post, comment, or user ID.
$taxonomystringrequired-
Taxonomy name.
Source
function get_object_term_cache( $id, $taxonomy ) {
$_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
// We leave the priming of relationship caches to upstream functions.
if ( false === $_term_ids ) {
return false;
}
// Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
$term_ids = array();
foreach ( $_term_ids as $term_id ) {
if ( is_numeric( $term_id ) ) {
$term_ids[] = (int) $term_id;
} elseif ( isset( $term_id->term_id ) ) {
$term_ids[] = (int) $term_id->term_id;
}
}
// Fill the term objects.
_prime_term_caches( $term_ids );
$terms = array();
foreach ( $term_ids as $term_id ) {
$term = get_term( $term_id, $taxonomy );
if ( is_wp_error( $term ) ) {
return $term;
}
$terms[] = $term;
}
return $terms;
}