Delete images of a particular size

Yap, a similar things happened to us once. And one of our senior developer and my teacher, Ms. Tahmina Akter, made the following code for us. Though it’s too rough, and there are some deprecated PHP functions too (I fixed them and updated the code), but it works.

CAUTION: Handle it with PROPER CARE, because it’s DEVASTATING.

How the code works:

  1. As it’s a page template, place the file within your theme, add a new Page, and choose the template there
  2. Change $_DELETE_IMAGES = false; to true to trigger the code.
  3. $filename = $up_dir['basedir'] . '/2013/12/'; here, mention each of the folder of your /uploads/ directory, from where you want to delete bunch of images
  4. As WordPress stores all the image sizes with a common format, like:
    filename-WxH.ext, so we are targeting the width parameter, and ignoring the height portion, and saying if ( preg_match( '/\.(jpg|png|jpeg|gif)$/', $file ) ): match hyphen and the width we mentioned and the height can be whatever, and then proceed to the next step
  5. Now open the WordPress page once, and the code will be executed, and the rest of the code will delete the files from the /uploads/YYYY/MM/ directory

Each reload will execute the code once. So we hope each execution will delete all the bunch of images, but if till there are other unnecessary image sizes, you can go to Step#3 and change the sizes to that particular sizes and reload the page again to run the code to delete.

<?php
/**
 * Template Name: Remove Image
 */

$_DELETE_IMAGES = false;

if( $_DELETE_IMAGES ) {

    $upload_dir   = wp_upload_dir();

    $target_path  = $upload_dir['basedir'] .'/2018/03/';
    $images       = array();
    $sized_images = array();

    // Grab all the images first (jpg, png, jpeg, gif).
    $dir = opendir( $target_path );
    while ( $file = readdir( $dir ) ) {
        if ( preg_match( '/\.(jpg|png|jpeg|gif)$/', $file ) ) {
            $images[] = $file;
        }
    }

    // Keep images only of the defined sizes.
    while (sizeof($images) != 0){
        $img = array_pop($images);
        if ( preg_match("~\-300x~",$img) || preg_match("~\-624x~",$img) || preg_match("~\-570x~",$img) ) {
            $sized_images[] = $img;
        }
    }

    // Now iterate thorough grabbed images and delete/unlink() 'em
    while ( sizeof($sized_images) != 0 ) {
        $target_image = array_pop( $sized_images );
        $the_file     = $target_path . $target_image;

        if ( file_exists($the_file) ) {
            unlink($the_file); // delete the file
            printf( "File %s has been deleted.<br>", $the_file );
        } else {
            printf( "File %s cannont be deleted, because it&rsquo;s not existed.<br>", $the_file );
        }
    }

} else {
    echo 'Deletion of image is currently off';
}