Reputation: 76
We have a form that clients use to upload photos. These photos aren't used anywhere on the site, but are stored within a folder within the Wordpress Uploads folder. As you can expect, this folder gets rather large, so we currently prune it manually. Wordpress upon picture upload, generates several versions of the picture, we use the 1024x768 version specifically.
I've been looking into setting up a WP-Cron job that runs every week or so that will automatically prune this for us. By date, and by filename. Specifically anything older than 15 days AND anything that has '1024x768' in the filename.
I currently have a plugin that is managing WP-Cron jobs, and only requires the php to be executed. This is what I have tried:
$files = glob(ABSPATH . UPLOADS . "/formidable/9/*");
$now = time();
foreach ($files as $file) {
if (is_file($file)) {
if ($now - filemtime($file) >= 60 * 60 * 24 * 15) { // 15 days
wp_delete_file($file);
}
}
}
I haven't bothered with the filename matching yet because even just pruning anything older than 15 days is probably going to be enough to keep disk usage down. And I can't figure out how to do that. Although I suspect I might be able to accomplish that with a specific glob definition. I'm a hack dev when it comes to PHP, so this is after a lot of google searching and stuff.
EDIT: Yeah, I failed and said to define older than AND the filename, when it was supposed to be everything BUT files with that in the name. The only files I want to keep are within 15 days, and include 1024x768 in the filename.
Upvotes: 1
Views: 527
Reputation: 3948
This will delete images that are older than 15 days or that don't have the "1024x768" string in the filename:
$files = glob(ABSPATH . UPLOADS . "/formidable/9/*");
$now = time();
foreach ($files as $file) {
if (is_file($file)) {
if (
( $now - filemtime($file) >= 60 * 60 * 24 * 15 ) // image is 15+ days old
|| strpos( $file, "1024x768" ) === false // image's filename doesn't have "1024x768" in it
) {
wp_delete_file($file);
}
}
}
Upvotes: 1
Reputation: 356
$files = glob(ABSPATH . UPLOADS . "/formidable/9/*");
$now = time();
foreach ($files as $file) {
if (is_file($file)) {
if ($now - filemtime($file) >= 60 * 60 * 24 * 15 // 15 days
|| preg_match('#1024x768#', $file)) {
wp_delete_file($file);
}
}
}
Edit: incase it's unclear, I've added preg_match('#1024x768#', $file)
which matches the files you described. The preg_match returns true on a match, so it will match that or the time.
Upvotes: 1