函数文档

get_available_post_mime_types()

💡 云策文档标注

概述

get_available_post_mime_types() 函数用于获取指定文章类型的所有可用 MIME 类型。它通过查询数据库或应用过滤器来返回一个 MIME 类型数组。

关键要点

  • 参数 $type 为字符串类型,通常默认为 'attachment',但可以是任何文章类型。
  • 返回值是一个字符串数组,包含所有可用的 MIME 类型。
  • 函数内部使用 apply_filters() 钩子 'pre_get_available_post_mime_types' 来过滤 MIME 类型列表。
  • 如果过滤器未返回数组,函数会查询数据库获取 DISTINCT post_mime_type。
  • 函数会移除返回数组中的 null 值,确保输出纯净。

代码示例

function get_available_post_mime_types( $type = 'attachment' ) {
    global $wpdb;

    $mime_types = apply_filters( 'pre_get_available_post_mime_types', null, $type );

    if ( ! is_array( $mime_types ) ) {
        $mime_types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s AND post_mime_type != ''", $type ) );
    }

    return array_values( array_filter( $mime_types ) );
}

注意事项

  • 函数自 WordPress 2.5.0 版本引入,并在 6.4.0 版本添加了过滤器钩子。
  • 相关函数包括 wpdb::get_col()、apply_filters() 和 wpdb::prepare(),用于数据库查询和钩子处理。
  • 该函数被 wp_edit_attachments_query() 使用,用于附件查询。

📄 原文内容

Gets all available post MIME types for a given post type.

Parameters

$typestringrequired

Return

string[] An array of MIME types.

Source

function get_available_post_mime_types( $type = 'attachment' ) {
	global $wpdb;

	/**
	 * Filters the list of available post MIME types for the given post type.
	 *
	 * @since 6.4.0
	 *
	 * @param string[]|null $mime_types An array of MIME types. Default null.
	 * @param string        $type       The post type name. Usually 'attachment' but can be any post type.
	 */
	$mime_types = apply_filters( 'pre_get_available_post_mime_types', null, $type );

	if ( ! is_array( $mime_types ) ) {
		$mime_types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s AND post_mime_type != ''", $type ) );
	}

	// Remove nulls from returned $mime_types.
	return array_values( array_filter( $mime_types ) );
}

Hooks

apply_filters( ‘pre_get_available_post_mime_types’, string[]|null $mime_types, string $type )

Filters the list of available post MIME types for the given post type.

Changelog

Version Description
2.5.0 Introduced.