Skip to content

Instantly share code, notes, and snippets.

@mesaque
Last active August 2, 2018 13:27
Show Gist options
  • Save mesaque/8e0af2c684e86c3b5d2b580e707c47dd to your computer and use it in GitHub Desktop.
Save mesaque/8e0af2c684e86c3b5d2b580e707c47dd to your computer and use it in GitHub Desktop.
Disable image crop
<?php
defined( 'ABSPATH' ) or exit;
/* Plugin Name: Disable image crop */
$custom_sizes = array('thumbnail'=>'150x150', 'medium'=>'210x300');
add_filter( 'image_resize_dimensions', 'apikiDisableCrop', 10, 6 );
function apikiDisableCrop( $enable, $orig_w, $orig_h, $dest_w, $dest_h, $crop )
{
return false;
}
add_filter( 'wp_generate_attachment_metadata' ,'apikiGenerateMetadata', 10, 2 );
function apikiGenerateMetadata( $metadata, $attachment_id )
{
global $custom_sizes;
$metadata_sizes = $metadata['sizes'];
$current_sizes = wp_get_additional_image_sizes();
$file = get_attached_file( $attachment_id );
$file_parts = pathinfo ( $file );
foreach ($custom_sizes as $key_name => $size):
$size_explode = explode('x', $size);
$metadata_sizes[$key_name] = array(
'file' => sprintf('%s-%dx%d.%s',
$file_parts['filename'],
$size_explode[0],
$size_explode[1],
$file_parts['extension']
),
'width' => $size_explode[0],
'height' => $size_explode[1],
'mime-type' => mime_content_type( $file ),
);
endforeach;
foreach ($current_sizes as $key_name => $size ):
$file_name = sprintf('%s-%dx%d.%s',
$file_parts['filename'],
$size['width'],
$size['height'],
$file_parts['extension']
);
$metadata_sizes[$key_name] = array(
'file' => $file_name,
'width' => $size['width'],
'height' => $size['height'],
'mime-type' => mime_content_type( $file ),
);
endforeach;
$metadata['sizes'] = $metadata_sizes;
do_action('apiki_crop_handled', $metadata, $attachment_id );
return $metadata;
}
// WORDPRESS-DOMAIN/wp-json/image_sizes/v1/sizes
add_action( 'rest_api_init', function () {
register_rest_route( 'image_sizes/v1', '/sizes/', array(
'methods' => 'GET',
'callback' => 'get_image_sizes',
) );
} );
function get_image_sizes()
{
global $custom_sizes;
$current_sizes = wp_get_additional_image_sizes();
foreach ( $custom_sizes as $key_name => $size ):
$size_explode = explode('x', $size);
$current_sizes[$key_name] = array( 'width' => $size_explode[0], 'height' => $size_explode[1] );
endforeach;
return $current_sizes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment