概要
get_post_mime_typeフィルタは、WordPress内で添付ファイルのMIMEタイプを取得するために使用されます。このフィルタを使うことで、特定のポストタイプに対してMIMEタイプを変更したり、拡張したりすることが可能です。主に以下のような機能を実装する際によく使われます:
- 特定のファイル形式のMIMEタイプをカスタマイズする
- 新しいファイルタイプを追加する
- 添付ファイルのドキュメントタイプを判別する
- フロントエンドでのメディア表示を変更する
- 管理画面でのメディアライブラリの表示を変更する
- プラグインやテーマが特定のファイルを認識できるようにする
- バルクアクションやメディアのアップロード時にMIMEタイプを検証する
- 適切なMIMEタイプを設定することでSEOを向上させる
構文
add_filter('get_post_mime_type', 'custom_get_post_mime_type', 10, 2);
パラメータ
$mime_type(string): 対象のポストのMIMEタイプ。$post_id(int): ポストのID。
戻り値
変更されたMIMEタイプ(string)。
関連する関数
https://refwp.com/?titleonly=1&s=get_post_mime_type
使用可能なバージョン
このフィルタはWordPressのバージョン3.0以降で使用可能です。
コアファイルのパス
wp-includes/post.php
この関数のアクションでの使用可能性
| アクション | 使用例 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | |
| register_sidebar | |
| wp_loaded | |
| send_headers | |
| parse_query | |
| pre_get_posts | |
| wp | |
| template_redirect | |
| get_header | |
| wp_head |
サンプルコード
サンプルコード1:特定のMIMEタイプを変更
add_filter('get_post_mime_type', 'change_image_mime_type', 10, 2);
function change_image_mime_type($mime_type, $post_id) {
if (get_post_type($post_id) == 'attachment') {
$mime_type = 'image/custom-image-type';
}
return $mime_type;
}
説明: このコードは、特定の条件下で画像のMIMEタイプをカスタムMIMEタイプに変更します。
サンプルコード2:新しいファイル形式を追加
add_filter('get_post_mime_type', 'add_custom_file_type', 10, 2);
function add_custom_file_type($mime_type, $post_id) {
if (strpos(get_attached_file($post_id), '.custom') !== false) {
$mime_type = 'application/x-custom';
}
return $mime_type;
}
説明: .custom拡張子を持つファイルが添付された場合に、特定のMIMEタイプを設定します。
サンプルコード3:MIMEタイプのロギング
add_filter('get_post_mime_type', 'log_mime_type', 10, 2);
function log_mime_type($mime_type, $post_id) {
error_log('MIME Type: ' . $mime_type . ' for Post ID: ' . $post_id);
return $mime_type;
}
説明: 添付ファイルのMIMEタイプをエラーログに記録します。
サンプルコード4:条件に基づくMIMEタイプの変更
add_filter('get_post_mime_type', 'conditional_mime_type', 10, 2);
function conditional_mime_type($mime_type, $post_id) {
if (strpos($mime_type, 'video/') === 0) {
return 'video/custom-video-type';
}
return $mime_type;
}
説明: 動画のMIMEタイプを特定のカスタムMIMEタイプに変更します。
サンプルコード5:特定のポストタイプでのフィルタリング
add_filter('get_post_mime_type', 'filter_mime_by_post_type', 10, 2);
function filter_mime_by_post_type($mime_type, $post_id) {
if (get_post_type($post_id) === 'my_custom_post_type') {
return 'application/my-custom-type';
}
return $mime_type;
}
説明: 特定のカスタムポストタイプに対してMIMEタイプを設定します。このコードはカスタムポストタイプの特定の条件に基づいてMIMEタイプを変更します。