Skip to content

Instantly share code, notes, and snippets.

@alanef
Last active January 20, 2021 11:09
Show Gist options
  • Select an option

  • Save alanef/c70819c94f9712e2b73cd78ac5dbbee3 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/c70819c94f9712e2b73cd78ac5dbbee3 to your computer and use it in GitHub Desktop.
<?php
/*
* Plugin Name: Clean media files in trash
*
* Plugin URI: https://fullworks.net/products/the-webinar-toolkit/
* Description: add define('EMPTY_MEDIA_TRASH_DAYS', 7); to wp-config.php
* Version: 1.0
* Author: Fullworks
* Author URI: https://fullworks.net/
* Licence: GPL 2 or later
*
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
/*
* set up an daily cron job
*
* ideally would also remove the scheduled event on plugin deactivation / uninstall -
* but it isn't that critical just will try and run and fail once the next day after deactivation
* see https://developer.wordpress.org/reference/functions/register_deactivation_hook/ and
* https://developer.wordpress.org/reference/functions/register_uninstall_hook/
*
*/
if ( ! wp_next_scheduled( 'myown_image_clean' ) ) {
wp_schedule_event( time(), 'daily', 'myown_image_clean' );
}
/*
* cleaning
*/
add_action(
'myown_image_clean',
function () {
if ( ! defined( 'EMPTY_MEDIA_TRASH_DAYS' ) ) {
return; // do nothing if not defined
}
$args = array(
'post_type' => 'attachment',
'posts_per_page' => - 1,
'post_status' => 'trash',
'date_query' => array(
array(
'before' => '-' . EMPTY_MEDIA_TRASH_DAYS .' days',
),
),
);
$attachments = get_posts( $args );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment