Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active May 18, 2020 14:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Resize images that are NOT attachments [WordPress]
/**
* In this example book covers are stored in custom fields.
* The max size used on site for book cover 300px *450px, so there is no point to store image large than this.
* We'll resize all existing book covers to this size using GD library.
* This is popular PHP image processor widely supported by hosting providers out of box.
* Also WordPress itself has got in-built support for that through WP_Image_Editor_GD class. Great for development!
**/
require_once( ABSPATH . 'wp-includes/class-wp-image-editor.php' );
require_once( ABSPATH . 'wp-includes/class-wp-image-editor-gd.php' );
//Get all bookcovers
$args = array( 'post_type' =>'post', 'posts_per_page' => -1, 'post_status' => 'any', 'fields' =>'ids');
$myposts = get_posts( $args );
foreach ($myposts as $mypostid) {
$bookcover = get_field('bookcover', $mypostid);
//Image options for resize
$max_w = 300;
$max_h = 450;
$crop = false;
$uploads_dir = wp_upload_dir();
$replace = $uploads_dir['basedir'];
$search = $uploads_dir['baseurl'];
//We need path here not url
$image_path = str_replace($search, $replace, $oblojka_knigi);
$gd_image_editor = new WP_Image_Editor_GD($image_path);
$gd_image_editor->load();
$current_size = $gd_image_editor->get_size();
//Proceed only with images that are larger than desired size
if (($current_size[width] > $max_w) || ($current_size[height] > $max_h)){
$gd_image_editor->resize( $max_w,$max_h,$crop);
$result = $gd_image_editor->save($image_path);
//print_r($result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment