Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Resize images in WordPress with in-built GD Image Editor [WordPress]
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
You can’t perform that action at this time.