Skip to content

Instantly share code, notes, and snippets.

@trepmal
Created December 29, 2011 00:22
Show Gist options
  • Save trepmal/1530664 to your computer and use it in GitHub Desktop.
Save trepmal/1530664 to your computer and use it in GitHub Desktop.
WordPress: Create missing intermediate images
<?php
/*
* @param int $id Image attachment ID
* @param string $size_name Name of custom image size as added with add_image_size()
* return bool True if intermediate image exists or was created. False if failed to create.
*/
function maybe_create_missing_intermediate_images( $id, $size_name ) {
$sizes = image_get_intermediate_size( $id, $size_name );
if ( ! $sizes ) { //if size doesn't exist for given image
//echo "new thumb need for id $id<br />";
$upload_dir = wp_upload_dir();
$image_path = str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], wp_get_attachment_url( $id ) );
$new = wp_generate_attachment_metadata( $id, $image_path );
wp_update_attachment_metadata( $id, $new );
if ( image_get_intermediate_size( $id, $size_name ) ) {
//echo "new image size created for id $id<br />";
return true;
}
else {
//echo "failed to create new image size for id $id<br />";
return false;
}
} else {
//echo 'already exists<br />';
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment