Is it possible to get WP to recognize added (past) year/month directories to /uploads?

44 Views Asked by At

I have 50,000 image files to upload and want to segment them into directories that I added to /uploads that match Wordpress' year/month directory naming and structure:

2010 -01 -02 -03 ...

These are months and years that do not show up in Media Library "All dates" filter because no file has been uploaded (via Media Library upload) during the actual month and year directory added.

I have added a test image to each month directory and then tried various plugins to register it to the media gallery. I thought I remember it working in the recent past with the Add from Server plug in, but I cant reproduce it. I have tried Regenerate Thumbnails plugin, Bulk Media Register plugin, Media Sync plugin, and as mentioned, Add from Server plugin. I have also tried "wp media regenerate --yes" through WP-CLI.

The problem seems to be that the images added do not have attachments, so WP doesn't register the directory.

I want the year/month directories to register to the Media Library so I can filter by "All dates" (without adding a different media gallery with a plugin like Media Library Folders Pro).

Without true technical understanding, I assume that segmenting the 50,000 images (which will turn into about 500,000 images after WP generates all the WP, Woocommerce, and theme thumbnails) would be faster served by the database if they were segmented into 300 directories instead of just one. Thoughts?

Thanks for any suggestions.

1

There are 1 best solutions below

3
Chad Phillips On

Here's the php code for adding an image to the WordPress Media Library. You'll need to set up a scheme for running batches of your images, as this will need to execute for each one.

$file_name = 'file_name'; // get the file name and assign it to this variable
    $date_folder_path = '/2024/01/'; // assign the correct path
// the file_name and folder path must lead to the correct image file inside the wp_uploads folder
    $publish_date = '2024-01-15  00:00:00';  //Assign a date having the year and month you want this to appear in the Media Library

// with these values set, your work is done and the following lines will add the image to the Media Library
                
$attachment = array();
$attachment['post_title'] = $file_name;
$attachment['post_content'] = '';
$attachment['post_status'] = 'publish';
$attachment['post_date'] = $publish_date;
$filename = $_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads/'.$date_folder_path.'.$file_name;
$attachment['post_mime_type'] = mime_content_type( $filename );
$media = wp_insert_attachment( $attachment, $filename, 0 ); // the 0 means you aren't attaching it to any particular post
$attach_data = wp_generate_attachment_metadata( $media, $filename ); 
wp_update_attachment_metadata( $media, $attach_data );