get_attachment_taxonomies()
云策文档标注
概述
get_attachment_taxonomies() 函数用于检索附件关联的分类法。它接受附件 ID、数组或对象作为参数,并支持返回分类法名称或对象数组。
关键要点
- 参数 $attachment 可以是整数(附件 ID)、数组或对象,必需
- 参数 $output 指定输出类型:'names' 返回分类法名称数组,'objects' 返回 WP_Taxonomy 对象数组,默认 'names'
- 返回值是字符串数组或 WP_Taxonomy 数组,失败时返回空数组
- 函数内部通过 get_object_taxonomies() 基于附件文件类型和 MIME 类型动态获取分类法
- 支持从 WordPress 4.7.0 版本引入的 $output 参数
代码示例
// 示例:获取附件 ID 为 123 的分类法名称
$taxonomies = get_attachment_taxonomies( 123, 'names' );
print_r( $taxonomies );
// 示例:获取附件对象的分类法对象
$attachment = get_post( 456 );
$taxonomies = get_attachment_taxonomies( $attachment, 'objects' );
print_r( $taxonomies );注意事项
- 确保 $attachment 参数有效,否则可能返回空数组
- 使用 'objects' 输出时,返回的数组可能包含重复项,需注意处理
- 函数依赖于 get_object_taxonomies() 和 get_attached_file() 等核心函数
原文内容
Retrieves taxonomies attached to given the attachment.
Parameters
$attachmentint|array|objectrequired-
Attachment ID, data array, or data object.
$outputstringrequired-
Output type.
'names'to return an array of taxonomy names, or'objects'to return an array of taxonomy objects.
Default is'names'.
Source
function get_attachment_taxonomies( $attachment, $output = 'names' ) {
if ( is_int( $attachment ) ) {
$attachment = get_post( $attachment );
} elseif ( is_array( $attachment ) ) {
$attachment = (object) $attachment;
}
if ( ! is_object( $attachment ) ) {
return array();
}
$file = get_attached_file( $attachment->ID );
$filename = wp_basename( $file );
$objects = array( 'attachment' );
if ( str_contains( $filename, '.' ) ) {
$objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
}
if ( ! empty( $attachment->post_mime_type ) ) {
$objects[] = 'attachment:' . $attachment->post_mime_type;
if ( str_contains( $attachment->post_mime_type, '/' ) ) {
foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
if ( ! empty( $token ) ) {
$objects[] = "attachment:$token";
}
}
}
}
$taxonomies = array();
foreach ( $objects as $object ) {
$taxes = get_object_taxonomies( $object, $output );
if ( $taxes ) {
$taxonomies = array_merge( $taxonomies, $taxes );
}
}
if ( 'names' === $output ) {
$taxonomies = array_unique( $taxonomies );
}
return $taxonomies;
}