fix: upload_media MIME detection; update_media/delete_media return correct media_id; getMedia adds media_id field

This commit is contained in:
2026-06-02 11:30:46 +00:00
parent 4b3f2916ff
commit f90c890865
+66 -13
View File
@@ -10,7 +10,6 @@ class MediaTools {
$qArgs = ['post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => (int) ($args['per_page'] ?? 20), 'paged' => (int) ($args['page'] ?? 1)]; $qArgs = ['post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => (int) ($args['per_page'] ?? 20), 'paged' => (int) ($args['page'] ?? 1)];
if (!empty($args['mime_type'])) $qArgs['post_mime_type'] = $args['mime_type']; if (!empty($args['mime_type'])) $qArgs['post_mime_type'] = $args['mime_type'];
if (!empty($args['search'])) $qArgs['s'] = $args['search']; if (!empty($args['search'])) $qArgs['s'] = $args['search'];
$query = new \WP_Query($qArgs); $query = new \WP_Query($qArgs);
$items = []; $items = [];
foreach ($query->posts as $p) { foreach ($query->posts as $p) {
@@ -24,7 +23,7 @@ class MediaTools {
$post = get_post($id); $post = get_post($id);
if (!$post || $post->post_type !== 'attachment') throw new \RuntimeException("Media not found: {$id}"); if (!$post || $post->post_type !== 'attachment') throw new \RuntimeException("Media not found: {$id}");
$meta = wp_get_attachment_metadata($id); $meta = wp_get_attachment_metadata($id);
return ['id' => $id, 'title' => $post->post_title, 'url' => wp_get_attachment_url($id), 'mime_type' => $post->post_mime_type, 'alt' => get_post_meta($id, '_wp_attachment_image_alt', true), 'caption' => $post->post_excerpt, 'description' => $post->post_content, 'metadata' => $meta]; return ['id' => $id, 'media_id' => $id, 'title' => $post->post_title, 'url' => wp_get_attachment_url($id), 'mime_type' => $post->post_mime_type, 'alt' => get_post_meta($id, '_wp_attachment_image_alt', true), 'caption' => $post->post_excerpt, 'description' => $post->post_content, 'metadata' => $meta];
} }
public static function uploadMedia(array $args): array { public static function uploadMedia(array $args): array {
@@ -36,11 +35,61 @@ class MediaTools {
$tmpFile = download_url($sourceUrl); $tmpFile = download_url($sourceUrl);
if (is_wp_error($tmpFile)) throw new \RuntimeException($tmpFile->get_error_message()); if (is_wp_error($tmpFile)) throw new \RuntimeException($tmpFile->get_error_message());
$fileName = basename(parse_url($sourceUrl, PHP_URL_PATH)); // Derive a clean filename with proper extension
$fileArray = ['name' => $fileName, 'tmp_name' => $tmpFile]; $urlPath = parse_url($sourceUrl, PHP_URL_PATH);
$postId = $args['post_id'] ?? 0; $fileName = basename($urlPath ?: 'upload');
$mediaId = media_handle_sideload($fileArray, (int) $postId); // Detect MIME type from the downloaded file to avoid WP type-checking failures
$mimeType = '';
if (function_exists('mime_content_type')) {
$mimeType = mime_content_type($tmpFile) ?: '';
}
if (empty($mimeType) && function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $tmpFile) ?: '';
finfo_close($finfo);
}
// Ensure the filename has the correct extension for the detected MIME type
if ($mimeType) {
$ext_map = [
'image/jpeg' => 'jpg',
'image/jpg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/webp' => 'webp',
'image/svg+xml' => 'svg',
'image/avif' => 'avif',
'video/mp4' => 'mp4',
'video/webm' => 'webm',
'audio/mpeg' => 'mp3',
'audio/wav' => 'wav',
'application/pdf' => 'pdf',
];
$detectedExt = $ext_map[$mimeType] ?? null;
if ($detectedExt) {
$baseName = pathinfo($fileName, PATHINFO_FILENAME) ?: 'upload';
$fileName = $baseName . '.' . $detectedExt;
}
}
$fileArray = [
'name' => $fileName,
'tmp_name' => $tmpFile,
'type' => $mimeType ?: 'application/octet-stream',
];
$postId = (int) ($args['post_id'] ?? 0);
// Temporarily allow all MIME types if WP blocks the detected type
add_filter('upload_mimes', function($mimes) use ($mimeType, $fileArray) {
if ($mimeType) {
$ext = pathinfo($fileArray['name'], PATHINFO_EXTENSION);
if ($ext) $mimes[$ext] = $mimeType;
}
return $mimes;
}, 99);
$mediaId = media_handle_sideload($fileArray, $postId);
@unlink($tmpFile); @unlink($tmpFile);
if (is_wp_error($mediaId)) throw new \RuntimeException($mediaId->get_error_message()); if (is_wp_error($mediaId)) throw new \RuntimeException($mediaId->get_error_message());
@@ -49,24 +98,29 @@ class MediaTools {
if (!empty($args['alt_text'])) update_post_meta($mediaId, '_wp_attachment_image_alt', $args['alt_text']); if (!empty($args['alt_text'])) update_post_meta($mediaId, '_wp_attachment_image_alt', $args['alt_text']);
if (!empty($args['caption'])) wp_update_post(['ID' => $mediaId, 'post_excerpt' => $args['caption']]); if (!empty($args['caption'])) wp_update_post(['ID' => $mediaId, 'post_excerpt' => $args['caption']]);
return ['id' => $mediaId, 'url' => wp_get_attachment_url($mediaId)]; return ['media_id' => $mediaId, 'id' => $mediaId, 'url' => wp_get_attachment_url($mediaId)];
} }
public static function updateMedia(array $args): array { public static function updateMedia(array $args): array {
$id = (int) $args['media_id']; $id = (int) $args['media_id'];
if (!$id) throw new \RuntimeException("media_id is required.");
$post = get_post($id);
if (!$post || $post->post_type !== 'attachment') throw new \RuntimeException("Media not found: {$id}");
$data = ['ID' => $id]; $data = ['ID' => $id];
if (isset($args['title'])) $data['post_title'] = $args['title']; if (isset($args['title'])) $data['post_title'] = $args['title'];
if (isset($args['caption'])) $data['post_excerpt'] = $args['caption']; if (isset($args['caption'])) $data['post_excerpt'] = $args['caption'];
if (isset($args['description'])) $data['post_content'] = $args['description']; if (isset($args['description'])) $data['post_content'] = $args['description'];
wp_update_post($data); if (count($data) > 1) wp_update_post($data);
if (isset($args['alt_text'])) update_post_meta($id, '_wp_attachment_image_alt', $args['alt_text']); if (isset($args['alt_text'])) update_post_meta($id, '_wp_attachment_image_alt', $args['alt_text']);
return ['id' => $id, 'updated' => true]; return ['media_id' => $id, 'id' => $id, 'updated' => true];
} }
public static function deleteMedia(array $args): array { public static function deleteMedia(array $args): array {
$result = wp_delete_attachment((int) $args['media_id'], (bool) ($args['force'] ?? true)); $id = (int) $args['media_id'];
if (!$result) throw new \RuntimeException("Failed to delete media: {$args['media_id']}"); if (!$id) throw new \RuntimeException("media_id is required.");
return ['id' => (int) $args['media_id'], 'deleted' => true]; $result = wp_delete_attachment($id, (bool) ($args['force'] ?? true));
if (!$result) throw new \RuntimeException("Failed to delete media: {$id}");
return ['media_id' => $id, 'id' => $id, 'deleted' => true];
} }
public static function countMedia(array $args): array { public static function countMedia(array $args): array {
@@ -81,5 +135,4 @@ class MediaTools {
} }
return $counts; return $counts;
} }
} }