admin管理员组

文章数量:1122832

I'm writing a maintenance script for my own sites and one part is to clear out all .webp files, since my host now handles WebP conversion on the fly. I could easily traverse through all the sub-folders in the /uploads/ directory, however there's usually other folders in there created by plugins. Is there a way to get a list of only the year/month folders that WordPress created?

I know I can just validate the folder names to check if they're a 4 digit year, I'd just rather do this the "proper" way if it's available.

I'm writing a maintenance script for my own sites and one part is to clear out all .webp files, since my host now handles WebP conversion on the fly. I could easily traverse through all the sub-folders in the /uploads/ directory, however there's usually other folders in there created by plugins. Is there a way to get a list of only the year/month folders that WordPress created?

I know I can just validate the folder names to check if they're a 4 digit year, I'd just rather do this the "proper" way if it's available.

Share Improve this question asked Apr 2, 2024 at 10:13 GavinGavin 4147 silver badges21 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can use this WP function wp_get_upload_dir to know the uploads directory path. Please note different website can choose not to use "year/month" fashion folder structure so using this function we will be advisable.

And then for finding all webp file you can use FileSearchIterator of PHP

$fileScanner = new FileSearchIterator( UPLOAD_BASE_PATH, true, 
        array('webp'));

foreach($fileScanner as $file)
{
    unlink(UPLOAD_BASE_PATH.$file);
}

Note: Code is not tested but hope this should work

本文标签: Get all WordPresscreated sub folders in uploads directory