I am looking for solution to auto delete images of old posts in WordPress site. I want to hold images of current 50 posts, others should be deleted automatically. It can be function to delete on time interval, or function to hold only images of last 50 posts. Does anyone know function or some plugin which can do this or similar things, to automatically delete older images? I believe that setting a cron job will be needed.
Someone posted this function in stackoverflow but I don’t see any mention of time.
function delete_post_media( $post_id ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
) );
foreach ( $attachments as $attachment ) {
if ( false === wp_delete_attachment( $attachment->ID ) ) {
// Log failure to delete attachment.
}
}
}
If you need to retain only images for last 50 posts, I don’t think that a cron job or a WP cron is the best thing you can do, in WordPress you can know when a post is published, and you can run a routine everytime it happen, deleting images for the post pubblished 50 posts ago.
That’s easy, better performing (you do nothing if you have nothing to do, a cron job runs regardless you have something to delete or not).
The workflow is pretty easy:
the code:
This works for posts published after you put the code in the site, but you can write a run-once function to delete images for older posts