Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save annalinneajohansson/10587098 to your computer and use it in GitHub Desktop.
Save annalinneajohansson/10587098 to your computer and use it in GitHub Desktop.
Ability to create image sizes on the fly in the_post_thumbnail(), using Matthew Ruddys Wordpress Timthumb Alternative (http://matthewruddy.github.io/Wordpress-Timthumb-alternative/)
<?php
/*
Simply put the desired image size in the_post_thumbnail( $size );
Sizes are declared as [height-in-pixels]x[width-in-pixels].
Example: the_post_thumbnail('400x300');
Dependencies: http://matthewruddy.github.io/Wordpress-Timthumb-alternative/
*/
add_filter( 'post_thumbnail_html', 'matthewruddy_post_thumbnail_resize', 20, 5 );
function matthewruddy_post_thumbnail_resize( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
$sizes = get_intermediate_image_sizes();
$sizes[] = 'full';
$defined_size = explode( "x", $size );
if( !in_array( $size, $sizes ) && count( $defined_size ) == 2 ) {
$src = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );
if( !isset( $attr['data-crop'] ) && $attr['data-crop'] == 0 ) $crop = false;
$img = matthewruddy_image_resize( $src[0], $defined_size[0], $defined_size[1] );
$html = hip_replace_img_src( $html, $img['url'], $img['width'], $img['height'] );
}
return $html;
}
function hip_replace_img_src( $original_img_tag, $new_src_url, $new_width = false, $new_height = false ) {
$doc = new DOMDocument();
$doc->loadHTML( $original_img_tag );
$images = $doc->getElementsByTagName('img');
if( count( $images ) > 0 ) {
$image = $images->item(0);
$image->setAttribute( 'src', $new_src_url );
if( $new_width ) $image->setAttribute( 'width', $new_width );
if( $new_height ) $image->setAttribute( 'height', $new_height );
return $doc->saveXML( $image );
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment