Created
April 12, 2012 12:46
-
-
Save rnagle/2366998 to your computer and use it in GitHub Desktop.
WordPress: Generate thumbnails on-the-fly
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
<?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