get_object_subtype()
云策文档标注
概述
get_object_subtype() 函数用于根据对象类型和ID返回其子类型,主要应用于元数据处理场景。它支持多种对象类型,如 'post'、'term'、'comment'、'user' 等,并通过内部逻辑和过滤器提供灵活扩展。
关键要点
- 函数接受两个参数:$object_type(对象类型字符串,如 'post'、'term')和 $object_id(对象ID整数)。
- 返回值是对象子类型字符串,若未指定则返回空字符串。
- 内部通过 switch 语句处理不同对象类型:对于 'post' 返回 post_type,对于 'term' 返回 taxonomy,对于 'comment' 和 'user' 返回固定字符串。
- 提供动态过滤器 apply_filters( "get_object_subtype_{$object_type}", $object_subtype, $object_id ) 以允许自定义子类型。
- 函数自 WordPress 4.9.8 版本引入,常用于元数据相关函数如 add_metadata()、update_metadata() 中。
代码示例
// 获取一个帖子的子类型(即 post_type)
$subtype = get_object_subtype( 'post', 123 );
// 可能返回 'post'、'page' 或自定义文章类型字符串
// 获取一个分类项的子类型(即 taxonomy)
$subtype = get_object_subtype( 'term', 456 );
// 可能返回 'category'、'post_tag' 或自定义分类法字符串注意事项
- 确保传入的 $object_type 是有效的对象类型,否则函数可能返回空字符串。
- 对于 'blog' 类型,文档未提供具体实现,需依赖过滤器或自定义处理。
- 函数内部使用 get_post_type()、get_term() 等辅助函数,确保对象存在以避免错误。
原文内容
Returns the object subtype for a given object ID of a specific type.
Parameters
$object_typestringrequired-
Type of object metadata is for. Accepts
'blog','post','comment','term','user', or any other object type with an associated meta table. $object_idintrequired-
ID of the object to retrieve its subtype.
Source
function get_object_subtype( $object_type, $object_id ) {
$object_id = (int) $object_id;
$object_subtype = '';
switch ( $object_type ) {
case 'post':
$post_type = get_post_type( $object_id );
if ( ! empty( $post_type ) ) {
$object_subtype = $post_type;
}
break;
case 'term':
$term = get_term( $object_id );
if ( ! $term instanceof WP_Term ) {
break;
}
$object_subtype = $term->taxonomy;
break;
case 'comment':
$comment = get_comment( $object_id );
if ( ! $comment ) {
break;
}
$object_subtype = 'comment';
break;
case 'user':
$user = get_user_by( 'id', $object_id );
if ( ! $user ) {
break;
}
$object_subtype = 'user';
break;
}
/**
* Filters the object subtype identifier.
*
* The dynamic portion of the hook name, `$object_type`, refers to the meta object type
* (blog, post, comment, term, user, or any other type with an associated meta table).
*
* Possible hook names include:
*
* - `get_object_subtype_blog`
* - `get_object_subtype_post`
* - `get_object_subtype_comment`
* - `get_object_subtype_term`
* - `get_object_subtype_user`
*
* @since 4.9.8
*
* @param string $object_subtype Object subtype or empty string to override.
* @param int $object_id ID of the object to get the subtype for.
*/
return apply_filters( "get_object_subtype_{$object_type}", $object_subtype, $object_id );
}
Hooks
- apply_filters( “get_object_subtype_{$object_type}”, string $object_subtype, int $object_id )
-
Filters the object subtype identifier.
Changelog
| Version | Description |
|---|---|
| 4.9.8 | Introduced. |