0

I am looking for solution to auto delete images (jpg, gif, png -content in general) inside a specific folder (folderx) INSIDE the uploads/months folders (customization intended for future folderx --older folderx have already been deleted manually). These images inside folderx have no relation to any posts. they can be deleted in x days. or x hours.

  • Uploads

    • O7 (month)
      • folderx (images inside folderx to be deleted)
    • O8 (month)
      • folderx (images inside folderx to be deleted)

    etc.etc

1 Answer 1

0

First of all, I would n e v e r automatically delete files, database entries, whathaveyou. Too risky. But, I created this once, that moves files to a 'trash' folder. This will help you get where you want:

/**
 * Autodelete folders in upload dir
 */
add_action('admin_init', function () {

    $time_to_live = 60 * 60 * 8; // 8 hours
    
    $folders_to_clean = [
        "2021/06",
        "2021/07",
    ];

    // dirs
    $upload_dir = wp_upload_dir();
    $upload_base = $upload_dir["basedir"];
    // loop through folders to clean
    foreach ($folders_to_clean as $folder) {
        // set specific trash path
        $trash_path = "{$upload_base}/_TRASH/{$folder}";
        // create trash path
        mkdir($trash_path, 0777, true);
        $folder_path = "{$upload_base}/{$folder}";
        // loop through files in dir
        if (is_dir($folder_path) && $handle = opendir($folder_path)) {
            // valid file?
            while (false !== ($file = readdir($handle))) {
                $file_path = "{$folder_path}/${file}";
                // older than set time?
                if (is_file($file_path) && filemtime($file_path) > $time_to_live) {
                    // move to trash
                    rename($file_path, "{$trash_path}/$file");
                }
            }
            closedir($handle);
        }
    }
});

If you do want to delete them immediately, just switch the rename function for unlink($file_path). But be warned, this will one day bite you hard! ;-)

2
  • as mentioned these images inside folderx have no relation to any posts "folderx", the images are not linked to any posts-- they are completely independent. so the trash option wont help. if it did somehow put it in trash, i think that would mess up everything. thank you for your reply though :) Jul 10, 2021 at 8:36
  • Then use the unlink command to delete them
    – Jos
    Jul 10, 2021 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.