Auto delete content in specific folder inside media library

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! 😉