Skip to content

Instantly share code, notes, and snippets.

@rnagle
Created April 12, 2012 12:46
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnagle/2366998 to your computer and use it in GitHub Desktop.
Save rnagle/2366998 to your computer and use it in GitHub Desktop.
WordPress: Generate thumbnails on-the-fly
<?php
/*
* Check for thumb of $size and generate it if it doesn't exist.
*
* @param int $post_id Post ID for which you want to retrieve thumbnail
* @param string $size Name of thumbnail size to check for; same as
* the slug used to add custom thumb sizes with add_image_size().
* @return array An array containing: array( 0 => url, 1 => width, 2 => height )
*
*/
function otf_get_attachment_image_src($post_id, $size = 'thumbnail', $force = false) {
$attachment_id = get_post_thumbnail_id($post_id);
$attachment_meta = wp_get_attachment_metadata($attachment_id);
$sizes = array_keys($attachment_meta['sizes']);
if ( in_array($size, $sizes) && empty($force) )
return wp_get_attachment_image_src($attachment_id, $size);
else {
include_once ABSPATH . '/wp-admin/includes/image.php';
$generated = wp_generate_attachment_metadata(
$attachment_id, get_attached_file($attachment_id));
$updated = wp_update_attachment_metadata($attachment_id, $generated);
return wp_get_attachment_image_src($attachment_id, $size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment