Export the Media Library List to CSV
Adds an "Export to CSV" bulk action to the Media Library list view that downloads the selected files with their URL, title, alt text, caption, type, size, dimensions and upload date.
Opens WPIDE on
Code
add_filter( 'bulk_actions-upload', function ( $actions ) {
$actions['wpide_export_media'] = 'Export to CSV';
return $actions;
} );
add_filter( 'handle_bulk_actions-upload', function ( $redirect, $action, $ids ) {
if ( 'wpide_export_media' !== $action || ! current_user_can( 'upload_files' ) ) {
return $redirect;
}
$rows = array( array( 'ID', 'URL', 'Title', 'Alt text', 'Caption', 'Type', 'File size', 'Width', 'Height', 'Uploaded' ) );
foreach ( $ids as $id ) {
if ( 'attachment' !== get_post_type( $id ) ) {
continue;
}
$meta = wp_get_attachment_metadata( $id );
$file = get_attached_file( $id );
$rows[] = array(
$id,
wp_get_attachment_url( $id ),
get_the_title( $id ),
get_post_meta( $id, '_wp_attachment_image_alt', true ),
wp_get_attachment_caption( $id ),
get_post_mime_type( $id ),
! empty( $meta['filesize'] ) ? $meta['filesize'] : ( $file && file_exists( $file ) ? filesize( $file ) : '' ),
$meta['width'] ?? '',
$meta['height'] ?? '',
get_the_date( 'Y-m-d', $id ),
);
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return $redirect;
}
nocache_headers();
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=media-' . gmdate( 'Y-m-d' ) . '.csv' );
$out = fopen( 'php://output', 'w' );
fwrite( $out, "\xEF\xBB\xBF" );
foreach ( $rows as $row ) {
fputcsv( $out, array_map( function ( $cell ) {
return is_string( $cell ) && preg_match( '/^[=+\-@]/', $cell ) ? "'" . $cell : $cell;
}, $row ) );
}
fclose( $out );
exit;
}, 10, 3 );
Notes
Handy for accessibility audits and migrations; switch the library to list view to see bulk actions.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.