How to export the Media Gallery
🔄 Re-evaluating Your WordPress Media Library? Generate a CSV Export in One Click!
Section titled “🔄 Re-evaluating Your WordPress Media Library? Generate a CSV Export in One Click!”As WordPress sites grow, so does the media library… and let’s be honest, it can become a bit of a jungle. Between outdated images, bloated PDFs, and unused assets, it’s easy to lose track of what’s actually useful.
That’s why I built a simple but powerful custom action hook in WordPress that exports all your media files into a clean CSV file. Why? Because sometimes you need to audit your uploads, understand what’s taking up space, or just get a bird’s eye view of what lives in your library.
What Does the CSV Include?
Section titled “What Does the CSV Include?”Every row gives you:
- 🖇 File Title (with link) – Click directly to edit each file in your WordPress admin.
- 📦 File Type – Whether it’s an image, video, document, etc.
- 📏 File Size in MB – So you know what’s hogging space.
- 🔗 “Uploaded To” URL – See which post or page the media is attached to (or not).
🛠️ How It Works
Section titled “🛠️ How It Works”Here’s the core function that makes the magic happen:
add_action('admin_post_exportar_media_csv', 'exportar_media_csv');
function exportar_media_csv() { if (!current_user_can('manage_options')) { wp_die('Unauthorized'); }
header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=media-export.csv');
$output = fopen('php://output', 'w'); fputcsv($output, ['File Title (linked)', 'File Type', 'File Size (MB)', 'Uploaded To (URL)']);
$media_query = new WP_Query([ 'post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => -1, ]);
foreach ($media_query->posts as $media) { $id = $media->ID; $title = get_the_title($id); $edit_link = admin_url("post.php?post={$id}&action=edit"); $linked_title = "=HYPERLINK(\"{$edit_link}\", \"{$title}\")";
$mime_type = get_post_mime_type($id); $file_path = get_attached_file($id); $file_size = $file_path ? round(filesize($file_path) / 1048576, 2) : 0;
$parent_id = $media->post_parent; $used_url = $parent_id ? get_permalink($parent_id) : '—';
fputcsv($output, [$linked_title, $mime_type, $file_size, $used_url]); }
fclose($output); exit;}✅ Why This Is Useful
Section titled “✅ Why This Is Useful”- Want to clean up unused media? You can easily spot items with no “Uploaded To” post.
- Need to report large files or export metadata? Done in seconds.
- Working on content audits or migrations? This gives your team a solid reference point.
📥 How to Use It
Section titled “📥 How to Use It”Set up a link or button that triggers a request to:
/wp-admin/admin-post.php?action=exportar_media_csvJust make sure the user is logged in and has the right capabilities (manage_options) to avoid unauthorized access 🔐.
Knowledge Check
Test your understanding of this section
Loading questions...