su_delete_resized_images

The shortcodes-ultimate su delete resized images function.

Published Date - February 15, 2021

Description

Deletes the resized images when the original image is deleted from the WordPress Media Library.

su_delete_resized_images( $post_id );

Parameters

  1. $post_id


Usage

The following example is for adding a hook callback.

if ( !function_exists( 'su_delete_resized_images' ) ) {
    require_once ABSPATH . PLUGINDIR . 'shortcodes-ultimateshortcodes-ultimate/inc/core/tools.php';
}

// The input(s). 
$post_id = null;

// NOTICE! Understand what this does before running.
$result = su_delete_resized_images( $post_id );
            

Defined

The function is defined in the following location(s).

shortcodes-ultimate/inc/core/tools.php

function su_delete_resized_images( $post_id ) {

	// Get attachment image metadata
	$metadata = wp_get_attachment_metadata( $post_id );
	if ( ! $metadata ) {
		return;
	}

	// Do some bailing if we cannot continue
	if ( ! isset( $metadata['file'] ) || ! isset( $metadata['image_meta']['resized_images'] ) ) {
		return;
	}
	$pathinfo       = pathinfo( $metadata['file'] );
	$resized_images = $metadata['image_meta']['resized_images'];

	// Get WordPress uploads directory (and bail if it doesn't exist)
	$wp_upload_dir = wp_upload_dir();
	$upload_dir    = $wp_upload_dir['basedir'];
	if ( ! is_dir( $upload_dir ) ) {
		return;
	}

	// Delete the resized images
	foreach ( $resized_images as $dims ) {

		// Get the resized images filename
		$file = $upload_dir . '/' . $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '-' . $dims . '.' . $pathinfo['extension'];

		// Delete the resized image
		@unlink( $file );
	}
}