函数文档

get_post_mime_type()

💡 云策文档标注

概述

get_post_mime_type() 函数用于根据附件 ID 检索其 MIME 类型。它适用于任何文章类型,但主要用于附件处理。

关键要点

  • 参数 $post 可选,可以是整数(文章 ID)或 WP_Post 对象,默认为全局 $post,默认值为 null
  • 返回值:成功时返回 MIME 类型字符串,失败时返回 false
  • 内部实现基于 get_post() 获取文章对象,并访问 post_mime_type 属性
  • 常用于 REST API 控制器、图像编辑和元数据生成等场景

代码示例

// 示例:根据附件 MIME 类型返回图标路径
function get_icon_for_attachment($post_id) {
  $base = get_template_directory_uri() . "/images/icons/";
  $type = get_post_mime_type($post_id);
  switch ($type) {
    case 'image/jpeg':
    case 'image/png':
    case 'image/gif':
      return $base . "image.png"; break;
    case 'video/mpeg':
    case 'video/mp4': 
    case 'video/quicktime':
      return $base . "video.png"; break;
    case 'text/csv':
    case 'text/plain': 
    case 'text/xml':
      return $base . "text.png"; break;
    default:
      return $base . "file.png";
  }
}
// 调用示例:
echo '<img src="' . get_icon_for_attachment($post->ID) . '" />';

注意事项

  • WordPress 已提供 wp_mime_type_icon() 函数用于获取 MIME 类型图标,建议优先使用
  • 函数自 WordPress 2.0.0 版本引入

📄 原文内容

Retrieves the mime type of an attachment based on the ID.

Description

This function can be used with any post type, but it makes more sense with attachments.

Parameters

$postint|WP_Postoptional
Post ID or post object. Defaults to global $post.

Default:null

Return

string|false The mime type on success, false on failure.

Source

function get_post_mime_type( $post = null ) {
	$post = get_post( $post );

	if ( is_object( $post ) ) {
		return $post->post_mime_type;
	}

	return false;
}

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Return an icon image path according to the MIME type of the given post

    function get_icon_for_attachment($post_id) {
      $base = get_template_directory_uri() . "/images/icons/";
      $type = get_post_mime_type($post_id);
      switch ($type) {
        case 'image/jpeg':
        case 'image/png':
        case 'image/gif':
          return $base . "image.png"; break;
        case 'video/mpeg':
        case 'video/mp4': 
        case 'video/quicktime':
          return $base . "video.png"; break;
        case 'text/csv':
        case 'text/plain': 
        case 'text/xml':
          return $base . "text.png"; break;
        default:
          return $base . "file.png";
      }
    }
    // call it like this:
    echo '<img src="'.get_icon_for_attachment($my_attachment->ID).'" />';

    WordPress already has a function to get the mime type icon called wp_mime_type_icon
    https://developer.wordpress.org/reference/functions/wp_mime_type_icon/