Managing a WordPress media library with numerous images can be a daunting task. Sometimes, you may need to export all these images for various purposes, such as creating backups or performing bulk image operations. This custom PHP code allows you to export all the images in your WordPress media library to a CSV file for easy access and management.
Follow these steps to use the provided custom PHP code to export your WordPress media library images:
-
Open your theme's
functions.phpfile. -
Copy and paste the following code snippet into the
functions.phpfile:
/**
* Export all the WordPress website media images.
*
* This custom code exports all the media library images
* into a CSV file.
*
* How to use:
* Put this custom code into your theme's functions.php file
* and access the website home page with the ?magic-export parameter.
* Example: https://yourwebsite.com?magic-export
*
* The exported-images.csv file will be generated in your website's root folder,
* which you can access via a similar URL:
* https://yourwebsite.com/exported-images.csv
*/
function vkh_custom_export_all_the_images() {
// Check for 'magic-export' parameter in the URL to trigger the export.
if ( isset( $_GET['magic-export'] ) ) {
// Fetch all the images via a query.
$images = get_posts(
array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_status' => 'any',
)
);
// Check if images are found.
if ( $images ) {
// Open a CSV file.
$fp = fopen( ABSPATH . 'exported-images.csv', 'w' );
// Define the CSV headers.
$header_fields = array( 'ID', 'Title', 'URL', 'Original URL' );
// Put the CSV headers into the file.
fputcsv( $fp, $header_fields );
// Loop through the found images.
foreach ( $images as $image ) {
// Get image title.
$title = get_the_title( $image->ID );
// Get image original URL.
$orig_url = wp_get_original_image_url( $image->ID );
// Get attachment URL.
$url = wp_get_attachment_url( $image->ID );
// Prepare CSV row data.
$fields = array( $image->ID, $title, $url, $orig_url );
// Put the CSV row data into the file.
fputcsv( $fp, $fields );
}
// Close the file.
fclose( $fp );
}
}
}
// Call the function on the 'init' action.
add_action( 'init', 'vkh_custom_export_all_the_images' );-
Save the changes to your
functions.phpfile. -
Access your WordPress website's home page with the
?magic-exportparameter. For example:https://yourwebsite.com?magic-export -
The code will generate a CSV file named
exported-images.csvin your website's root folder. You can access this file using the following URL:https://yourwebsite.com/exported-images.csv
This custom PHP code simplifies the process of exporting all the images in your WordPress media library to a CSV file. It can be a valuable tool for managing and organizing your media assets more effectively.