How to Automatically Delete Images in WordPress After a Time Period

Learn how to delete images after a given period of time automatically. You can use a plugin or some custom code to accomplish this.

WordPress doesn’t include a built-in feature to automatically delete images after a specific time period or set an expiration date for media files. If you need to remove images based on their age – whether for temporary promotions, storage management, or compliance requirements – you’ll need to use a plugin or custom code to schedule this deletion.

This guide covers three methods to expire and automatically remove WordPress images after a set time:

  1. Media expiration plugins that let you set deletion dates for individual files
  2. Custom code with WordPress cron jobs to auto-delete images older than X days
  3. Alternative approaches for specific use cases

Each method has different advantages depending on whether you need per-image control or automatic scheduled cleanup. Let’s explore your options.

Why Automatically Delete Images After a Time Period?

There are several legitimate reasons to remove images based on their age rather than their usage:

Time-sensitive content: Event promotions, seasonal campaigns, or limited-time offers often include images that become irrelevant after a specific expiry date.

User-generated content policies: If your site allows uploads, you might need retention policies that automatically expire and remove content after 30, 60, or 90 days.

Storage management: Hosting plans with limited storage benefit from scheduled automatic cleanup of older files, especially for high-volume sites.

Compliance requirements: GDPR or other regulations might require automatic deletion of certain images after a retention period expires.

Temporary testing: Development or staging sites might need scheduled removal of test images to prevent clutter.

Unlike finding and removing unused images (which focuses on whether an image is currently displayed), time-based expiration removes files simply because they’ve reached a certain age—regardless of whether they’re still in use.

Screenshot of the WordPress media library with a filter set to show only images from October 2024 and highlighting the upload date in the Date column.
You can filter the Media Library list view by month in which the image was uploaded and see the upload date in the Date column.

Method 1: Using the Media Expirator Plugin

The Media Expirator plugin is specifically designed to delete media files after a set date automatically. It adds an expiration date field to each media item in your library.

Warning: This plugin hasn’t been updated in 10 years and has significant security flaws. I am only mentioning it here since it is the only dedicated plugin I’ve found. I’d not recommend using it in a production environment.

How it works:

  1. Install and activate the Media Expirator plugin from the WordPress plugin repository
  2. Open any image in your media library editor
  3. Enable the expiration feature for that specific image
  4. Set the expiration date when you want the file automatically deleted
  5. The plugin will remove the file from your media library when that date is reached, using a daily cron job in the background.
The option to set the expiration date for an image in the Media Expirator plugin.
The option to set the expiration date for an image in the Media Expirator plugin.

Advantages:

  • Per-image control over expiration dates
  • Simple interface integrated into the WordPress media editor
  • Can enable or disable expiry for individual files
  • No coding required

Limitations:

  • The code lacks security and should not be used on production sites
  • Requires manual date setting for each image
  • Not ideal for bulk operations or automatic age-based deletion
  • You need to remember to set expiration dates when uploading

This plugin works best when you know exactly when specific images should expire – such as promotional graphics for an event ending on a particular date.

Method 2: Custom Code to Delete Images by Age

For more automated control – such as deleting all images older than a specific number of days – custom code with WordPress cron jobs provides a flexible solution.

Code Snippet: Automatically Delete Images Older Than X Days

This code snippet uses WordPress’s built-in cron system to schedule automatic deletion of images based on their upload date. Add this to your theme’s functions.php file or use a plugin like Code Snippets.

<?php
// Schedule the image cleanup event
function schedule_old_image_deletion() {
    if (!wp_next_scheduled('delete_old_images_event')) {
        wp_schedule_event(time(), 'daily', 'delete_old_images_event');
    }
}
add_action('wp', 'schedule_old_image_deletion');

// Delete images older than specified days
function delete_old_images() {
    // Set how many days old images should be before deletion
    $days_old = 365; // Change this number to your desired age in days

    // Calculate the date threshold
    $date_threshold = date('Y-m-d', strtotime('-' . $days_old . ' days'));

    // Query for old image attachments
    $old_images = get_posts(array(
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1,
        'date_query'     => array(
            array(
                'before' => $date_threshold,
                'inclusive' => true,
            ),
        ),
    ));

    // Delete each old image
    foreach ($old_images as $image) {
        wp_delete_attachment($image->ID, true); // true = force delete, skip trash
    }
}
add_action('delete_old_images_event', 'delete_old_images');
?>Code language: PHP (php)

How to customize this code:

  • Change $days_old = 365; to your desired retention period (e.g., 90 for three months, 30 for one month)
  • Modify 'daily' to 'hourly' or 'twicedaily' to change how often the cleanup runs
  • Change true to false in wp_delete_attachment() to send images to trash instead of permanently deleting them

Important: This code permanently deletes images older than your specified threshold every time the scheduled event runs. Always back up your site before implementing automatic deletion code.

Code Snippet: Delete Images When Their Post is Deleted

If you want images to expire when their associated post is removed, this alternative approach automatically deletes attached media files whenever a post is deleted:

<?php
// Delete attached images when post is deleted
function delete_post_images($post_id) {
    // Get all attachments for this post
    $attachments = get_posts(array(
        'post_type'      => 'attachment',
        'posts_per_page' => -1,
        'post_parent'    => $post_id,
    ));

    // Delete each attachment
    foreach ($attachments as $attachment) {
        wp_delete_attachment($attachment->ID, true);
    }
}
add_action('before_delete_post', 'delete_post_images');
?>Code language: HTML, XML (xml)

This approach works well when combined with post-expiration plugins, such as PublishPress Future, to create a comprehensive content and media expiry system.

Note: This code removes images that were initially uploaded to a post, regardless of whether they were ever used in it or are used elsewhere. See How to remove unused images in WordPress for a deeper explanation and reliable solution.

Method 3: Consider Unused Images Instead

While time-based expiration has specific use cases, many WordPress sites actually benefit more from removing unused images rather than old ones. A photo uploaded three years ago might still be actively displayed on essential pages, while an image uploaded yesterday might already be orphaned and wasting space.

If your primary goal is storage optimization and performance improvement rather than compliance or time-sensitive content removal, identifying unused images provides a more targeted approach. This is a different strategy from automatic expiration, because it focuses on whether images are currently in use rather than their age.

For sites that need this approach, plugins like Image Source Control can identify genuinely unused images through comprehensive scanning. You can learn more about finding unused images in WordPress or explore the unused images feature.

Steps to remove unused images in a WordPress plugin.
With Image Source Control, you can manage unused images and run deep checks to make sure they don’t appear in content, options, and other meta data.

Important Considerations Before Auto-Deleting Images

Always Create a Backup First

Before implementing any automatic image deletion, whether through plugins or custom code, create a complete backup of your WordPress site. This includes both your database and your files (especially the wp-content/uploads directory where media files are stored).

Most hosting providers offer automated backup solutions, or you can use plugins like WP Staging, UpdraftPlus, or BackWPup.

Test in Staging First

If possible, test your expiration setup on a staging site before implementing it on your live website. This lets you verify that:

  • The correct images are being targeted for deletion
  • Your cron schedule runs as expected
  • No essential images are accidentally removed
  • The deletion process doesn’t cause performance issues

Conclusion

WordPress doesn’t offer a built-in image expiration functionality, but you have two main options to automatically delete images after a time period:

  • Media Expirator plugin for setting specific expiry dates on individual images
  • Custom code with WordPress cron jobs for automatic deletion of images older than X days

Each method serves different needs. If you need precise control over when specific images expire, use the Media Expirator plugin. If you want a fully automated cleanup based on age, implement custom code with scheduled cron jobs.

However, consider whether time-based deletion is really what you need. For most WordPress sites, removing unused images provides better results for storage optimization and performance improvement without the risk of deleting images that are still actively displayed.

If you’re interested in a safer approach that identifies genuinely unused images before deletion, explore Image Source Control’s unused images feature or check out the pricing options.

FAQ

Can WordPress automatically delete images after 1 year?

While WordPress core has no expiration feature, you can automatically delete images after one year using either the Media Expirator plugin (by setting individual expiration dates) or custom code with WordPress cron jobs (by setting $days_old = 365 in the code snippet above). The custom code approach is better for automatic bulk deletion based on age, while the plugin works well for setting specific expiry dates on individual images.

What happens to images when I delete them from WordPress?

When you delete an image from the WordPress media library, it’s first moved to the Trash (similar to posts and pages). From there, it’s permanently deleted after 30 days, or you can empty the trash manually. The image file is removed from your server’s wp-content/uploads directory, and all database references to that attachment are deleted. If the image was still being used on pages or posts, those locations will show a broken image.

How do I find images that haven’t been used in over a year?

WordPress doesn’t track when images were last displayed or used – only when they were uploaded. To find images unused for a specific time period, you’d need to combine two approaches: first identify all unused images (regardless of age), then filter that list by upload date. Image Source Control can scan for unused images and identify files not currently in use, which you can then manually review by upload date in your media library.

Can I automatically delete images from WooCommerce products?

Yes, but be extremely careful. Product images are critical for e-commerce functionality. If you’re using time-based deletion code, you can modify it to exclude WooCommerce product images by adding post parent checks or custom taxonomies to your query. However, automatically deleting product images based on age is generally not recommended unless you have a specific business model (like limited-time products) that requires it. For WooCommerce sites, manually reviewing and deleting images for discontinued products is usually safer.

Portrait of Thomas Maier, founder and CEO of Image Source Control

Questions? Feedback? How can I help?

Reach out directly via the contact form.