函数文档

get_taxonomies_for_attachments()

💡 云策文档标注

概述

get_taxonomies_for_attachments() 函数用于检索所有为附件注册的分类法,包括处理特定 MIME 类型的分类法如 attachment:image 和 attachment:video。

关键要点

  • 函数返回为附件注册的分类法名称或对象数组。
  • 参数 $output 控制输出类型,可选 'names' 或 'objects',默认为 'names'。
  • 函数内部通过遍历 get_taxonomies() 结果,筛选对象类型为 'attachment' 或以 'attachment:' 开头的分类法。

代码示例

function get_taxonomies_for_attachments( $output = 'names' ) {
    $taxonomies = array();

    foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
        foreach ( $taxonomy->object_type as $object_type ) {
            if ( 'attachment' === $object_type || str_starts_with( $object_type, 'attachment:' ) ) {
                if ( 'names' === $output ) {
                    $taxonomies[] = $taxonomy->name;
                } else {
                    $taxonomies[ $taxonomy->name ] = $taxonomy;
                }
                break;
            }
        }
    }

    return $taxonomies;
}

注意事项

  • 函数自 WordPress 3.5.0 版本引入。
  • 相关函数包括 get_taxonomies(),用于获取所有注册的分类法。
  • 在 AJAX 查询附件、媒体列表表列生成和 WP_Query 查询等场景中使用。

📄 原文内容

Retrieves all of the taxonomies that are registered for attachments.

Description

Handles mime-type-specific taxonomies such as attachment:image and attachment:video.

See also

Parameters

$outputstringoptional
The type of taxonomy output to return. Accepts 'names' or 'objects'.
Default 'names'.

Return

string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.

Source

function get_taxonomies_for_attachments( $output = 'names' ) {
	$taxonomies = array();

	foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
		foreach ( $taxonomy->object_type as $object_type ) {
			if ( 'attachment' === $object_type || str_starts_with( $object_type, 'attachment:' ) ) {
				if ( 'names' === $output ) {
					$taxonomies[] = $taxonomy->name;
				} else {
					$taxonomies[ $taxonomy->name ] = $taxonomy;
				}
				break;
			}
		}
	}

	return $taxonomies;
}

Changelog

Version Description
3.5.0 Introduced.