按年龄自动删除媒体库中的图片

时间:2018-11-15 作者:TravelWhere

我想自动删除媒体库中超过3天的图像。有没有办法做到这一点?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

您可以使用以下功能查找和删除自创建之日起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作业,并查看thisthis 了解更多详细信息。

结束

相关推荐

如何使用分类法获取图像(WP Media文件夹)

如何创建一个画廊页面,它是一个画廊的画廊-使用子画廊中的特定照片作为相册的封面?这就是我目前所拥有的。我在后端有一个使用WP Media folder构建的文件夹,名为master. 我想在图库页面中列出master 以及缩略图所属库的名称。这是我的。$galleries = get_terms( \'wpmf-gallery-category\', [ \'hide_empty\' => 0 ]); foreach ( $galleries as $gal )