Last active
May 18, 2020 14:11
-
-
Save sabrina-zeidan/9dd69de0ec87da10f081bee57d525f18 to your computer and use it in GitHub Desktop.
Resize images that are NOT attachments [WordPress]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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