首先,我会自动删除文件、数据库条目以及您认为的内容。太冒险了。但是,我创建了一次,它将文件移动到“垃圾”文件夹。这将帮助您实现您的目标:
/**
* 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);
}
}
});
如果确实要立即删除它们,只需切换
rename
功能
unlink($file_path)
. 但请注意,总有一天这会让你难受的!;-)