您可以使用以下功能查找和删除自创建之日起3天的图像附件:
// Delete attachments (images) that are {n} days old.
function auto_delete_old_image_atts() {
// How many days old.
$days = 3;
// TRUE = bypasses the trash and force deletion.
$force_delete = true;
// Get all attachments that are images.
$atts = get_posts( array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image/%\',
\'posts_per_page\' => -1,
\'post_days_old\' => $days,
\'suppress_filters\' => false,
) );
$current_date = current_time( \'mysql\' );
foreach ( $atts as $att ) {
// Get the number of days since the attachment was created.
$created_datetime = new DateTime( $att->post_date );
$current_datetime = new DateTime( $current_date );
$interval = $created_datetime->diff( $current_datetime );
// If the attachment is $days days old since its CREATION DATE, delete
// the attachment (post data and image) and all thumbnails.
if ( $interval->days >= $days ) {
wp_delete_attachment( $att->ID, $force_delete );
}
}
}
// Filter the query so that only posts which are {n} (e.g. 3) days old will be
// returned by MySQL. For this to work, use \'post_days_old\' when querying for
// posts using `get_posts()` or `new WP_Query()`.
add_filter( \'posts_clauses\', \'filter_posts_by_dates_days\', 10, 2 );
function filter_posts_by_dates_days( array $clauses, WP_Query $wp_query ) {
$days = $wp_query->get( \'post_days_old\' );
if ( is_numeric( $days ) && $days >= 0 ) {
global $wpdb;
$clauses[\'where\'] .= $wpdb->prepare( "
AND ( DATEDIFF( NOW(), {$wpdb->posts}.post_date ) >= %d )
", $days );
}
return $clauses;
}
出于优化目的,我们过滤
WP_Query
请求/查询,以便MySQL只选择和返回3天以前的帖子/附件;在
foreach
循环,我们使用PHP的内置
DateTime::diff()
功能,以确保每个帖子的实际发布时间为3天。
现在,对于自动删除部分,您可以使用wp_schedule_event
同上:(详见法典)
// Schedule an event that runs once in every hour.
add_action( \'init\', \'schedule_my_hourly_event\' );
function schedule_my_hourly_event() {
if ( ! wp_next_scheduled( \'my_hourly_event\' ) ) {
wp_schedule_event( time(), \'hourly\', \'my_hourly_event\' );
}
}
// Auto-check for old images and delete them, if any.
add_action( \'my_hourly_event\', \'auto_delete_old_image_atts\' );
或者您可以忽略上述代码并使用
WP Crontrol 而是添加cron事件。(请参阅插件页面以了解执行此操作的详细信息)
我建议你禁用wp-cron.php
是的,因为
auto_delete_old_image_atts()
可能需要
long (如果不是很长的话)需要很长时间才能完成,因此您应该使用“真正的”cron作业,并查看
this 和
this 了解更多详细信息。