Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active February 13, 2020 09:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/29a8a774be810d5f34ce6dac4842c16b to your computer and use it in GitHub Desktop.
Save wpmudev-sls/29a8a774be810d5f34ce6dac4842c16b to your computer and use it in GitHub Desktop.
[Smush] - Bulk Reset Meta Dimensions. The following snippet will check for images that seem to need Re-Smushing due to resize option and it will resize image, update meta with new dimensions and keep a backup of original. More specifically, when the Image Resizing option is enabled, some images that have meta dimensions greater than the ones in …
<?php
/**
* Plugin Name: [Smush] - Bulk Reset Meta Dimensions
* Plugin URI: https://premium.wpmudev.org/
* Description: The following snippet will check for images that seem to need Re-Smushing due to resize option and it will resize image, update meta with new dimensions and keep a backup of original. More specifically, when the Image Resizing option is enabled, some images that have meta dimensions greater than the ones in the resize option, keep appearing that they need Re-Smushing.
* Task: 0/11289012348292/1158345785486319
* Author: Panos Lyrakis @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( ! class_exists( 'WPMUDEV_Smush_Reset_Meta_Dimensions' ) ) {
class WPMUDEV_Smush_Reset_Meta_Dimensions {
private static $_instance = null;
private static $step = 10;
private static $current_step = 0;
private $smush_core = null;
private $smush_instance = null;
private $site_image_dimensions = array();
private $resize_sizes = array();
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Smush_Reset_Meta_Dimensions();
}
return self::$_instance;
}
private function __construct() {
if( ! defined( 'WP_SMUSH_VERSION' ) ){
return;
}
$this->setup();
add_action( 'admin_menu', array( $this, 'admin_menu' ), 20 );
add_action( 'wp_ajax_wpmudev_smush_reset_meta_dimensions', array( $this, 'bulk_image_meta_resize_ajax' ) );
}
private function setup() {
if ( is_null( $this->smush_core ) ) {
if ( version_compare( WP_SMUSH_VERSION, '3.5.0' ) >= 0 ) {
$this->smush_instance = WP_Smush::get_instance();
$this->smush_core = $this->smush_instance::get_instance()->core();
} else {
$this->smush_instance = Smush\WP_Smush::get_instance();
$this->smush_core = $this->smush_instance::get_instance()->core();
}
}
}
public function admin_menu() {
add_submenu_page(
'smush' ,
'Reset Meta Dimensions',
'Reset Meta Dimensions',
'manage_options',
'smush-reset-meta-dimensions',
array( $this, 'admin_page' )
);
}
public function bulk_image_meta_resize_ajax() {
$_post_data = @file_get_contents( 'php://input' );
$post_data = json_decode( $_post_data );
self::$current_step = $post_data->step;
if ( ! isset( $post_data->nonce ) || ! wp_verify_nonce( $post_data->nonce , 'wpmudev_smush_reset_meta_dimensions_nonce' ) ) {
$return = array(
'success' => false,
'message' => 'AJAX nonce is wrong'
);
wp_send_json( $return );
}
$images_to_resize = get_option( 'wp-smush-resmush-list', array() );
if ( empty( $images_to_resize ) ) {
$return = array(
'success' => false,
'message' => 'No images that need resizing'
);
wp_send_json( $return );
}
$this->resize_sizes = get_option( 'wp-smush-resize_sizes' );
$message = $this->regenerate_attachments_meta( $images_to_resize );
$return = array(
'success' => true,
'message' => $message,
'current_step' => self::$current_step
);
wp_send_json( $return );
}
public function regenerate_attachments_meta( $attachment_ids = array() ) {
$were_reset = array();
$response = '';
if ( empty( $attachment_ids ) ) {
$message = "There was no attachent id sent. Smething is wrong in the script.";
return $message;
}
foreach ( $attachment_ids as $attachment_id ) {
if ( $this->reset_image_dimensions( $attachment_id ) ) {
$were_reset[] = $attachment_id;
}
}
if ( empty( $were_reset ) ) {
$message = "We couldn't reset the meta dimensions for any image.";
} else {
$message = "The dimensions were succesfully reset for the following images <br /><strong>" . implode( ',', $were_reset ) . "</strong><br />You can try Re-checking images from Smush Dashboard!";
}
}
public function reset_image_dimensions( $attachment_id ) {
if ( empty( $this->resize_sizes ) || ! isset( $this->resize_sizes[ 'width' ] ) || ! isset( $this->resize_sizes[ 'height' ] ) ) {
return false;
}
$attachment_meta = wp_get_attachment_metadata( $attachment_id );
$attachment_meta[ 'width' ] = $this->resize_sizes[ 'width' ];
$attachment_meta[ 'height' ] = $this->resize_sizes[ 'height' ];
if ( $this->resize_image(
$attachment_id ,
$attachment_meta[ 'width' ],
$attachment_meta[ 'height' ]
)
) {
wp_update_attachment_metadata( $attachment_id, $attachment_meta );
return true;
}
return false;
}
public function resize_image( $attachment_id, $new_width, $new_height, $keep_backup = true ) {
$path = get_attached_file( $attachment_id );
if ( $keep_backup ) {
$this->create_backup( $path, $attachment_id );
}
$image = wp_get_image_editor( $path );
if ( ! is_wp_error( $image ) ) {
$image->resize( $new_width, $new_height, true );
$image->save( $path );
return true;
}
return false;
}
public function create_backup( $file_path = '', $attachment_id = '' ) {
$copied = false;
if ( empty( $file_path ) ) {
return false;
}
$mod = WP_Smush::get_instance()->core()->mod;
$backup_path = $this->get_image_backup_path( $file_path );
// If we don't have any backup path yet, bail!
if ( empty( $backup_path ) ) {
return $file_path;
}
if ( ! empty( $attachment_id ) && $mod->png2jpg->is_converted( $attachment_id ) ) {
// No need to create a backup, we already have one if enabled.
return false;
}
// Check for backup from other plugins, like nextgen, if it doesn't exists, create our own.
if ( ! file_exists( $backup_path ) ) {
$copied = @copy( $file_path, $backup_path );
}
return $copied;
}
protected function get_image_backup_path( $attachment_path ) {
// If attachment id is not available, return false.
if ( empty( $attachment_path ) ) {
return false;
}
$path = pathinfo( $attachment_path );
// If we don't have complete filename return false.
if ( empty( $path['extension'] ) ) {
return false;
}
$backup_name = trailingslashit( $path['dirname'] ) . $path['filename'] . '.bak2.' . $path['extension'];
return $backup_name;
}
public function admin_page() {
?>
<h1>Smush - Reset Image Meta Dimensions</h1>
<h4>When the <strong>Image Resizing</strong> option is enabled, there can cases where some pre-existing images have meta dimensions that are bigger than the ones set in the Image Resizing option. For those cases, those images will keep showing up for Re-Smush on every image re-check. In order to fix this, you can click on the button bellow. This will generate a new image with the proper dimmensions, keep a backup of the old (with a post fix "bak2") and update the meta values accordingly.</h4>
<div>
<button id="smush-bulk-restore">Reset Meta Dimensions</button>
<?php wp_nonce_field( 'wpmudev_smush_reset_meta_dimensions_nonce', 'wpmudev_smush_reset_meta_dimensions_nonce' ); ?>
</div>
<div id="wpmudev-bulk-smush-placeholer"></div>
<div id="wpmudev-bulk-smush-log"></div>
<script type="text/javascript">
($=>{
WPMUDEV_Smush_Reset_Meta_Dimensions = {
button : $( '#smush-bulk-restore' ),
log : $( '#wpmudev-bulk-smush-log' ),
placeholder : $( '#wpmudev-bulk-smush-placeholer' ),
current_step : 0,
init : function(){
this.button.on( 'click', this.run );
},
run : async function(){
let body = {
step : WPMUDEV_Smush_Reset_Meta_Dimensions.current_step,
nonce : $( '#wpmudev_smush_reset_meta_dimensions_nonce' ).val()
};
WPMUDEV_Smush_Reset_Meta_Dimensions.button.hide( 300, function(){ $(this).remove(); });
WPMUDEV_Smush_Reset_Meta_Dimensions.placeholder.html( '<h3>Please wailt while resteing dimensions on image meta. It might take a while</h3> <h4>Make sure you don\'t close or update this tab as the restoration process needs this tab open in order to complete</h4>' );
const response = await fetch( `${window.ajaxurl}?action=wpmudev_smush_reset_meta_dimensions`, {
method: 'POST', // or 'PUT'
body: JSON.stringify( body )
});
json = await response.json();
if ( json.success ) {
if ( '' === json.message || null === json.message || ! json.current_step ) {
WPMUDEV_Smush_Reset_Meta_Dimensions.placeholder.html( '<h3>Images meta dimensions have been reset</h3>' );
return;
}
WPMUDEV_Smush_Reset_Meta_Dimensions.log.append( json.message );
WPMUDEV_Smush_Reset_Meta_Dimensions.current_step = json.current_step;
WPMUDEV_Smush_Reset_Meta_Dimensions.run();
}
}
};
$(document).ready( WPMUDEV_Smush_Reset_Meta_Dimensions.init() );
})(jQuery);
</script>
<?php
}
private function log( $message ) {
if ( ! defined( "WP_DEBUG_LOG" ) || ! WP_DEBUG_LOG ) {
return;
}
$time = date( 'd-M-Y H:i:s' );
error_log(
"[ {$time} ] \n{$message}\n\n\n",
3,
WP_CONTENT_DIR . "/smush-debug.log"
);
}
}
if ( ! function_exists( 'wpmudev_smush_reset_meta_dimensions' ) ) {
function wpmudev_smush_reset_meta_dimensions(){
return WPMUDEV_Smush_Reset_Meta_Dimensions::get_instance();
};
add_action( 'plugins_loaded', 'wpmudev_smush_reset_meta_dimensions', 99 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment