Skip to content

Instantly share code, notes, and snippets.

@oranblackwell
Last active August 29, 2015 14:02
Show Gist options
  • Save oranblackwell/c1b27904e27c7b0f5fb9 to your computer and use it in GitHub Desktop.
Save oranblackwell/c1b27904e27c7b0f5fb9 to your computer and use it in GitHub Desktop.
Wordpress Responsive Images

Selectively Serve Images

Please note the naming convention for each pair.

<?php
/**
 * Set up custom image sizes
 *
 * @author Oran Blackwell
 */

/* News */
add_image_size( 'news-lead', 645, 370, true );
add_image_size( 'news-lead-mobile', 737, 513, true );

add_image_size( 'news-medium', 200, 136, true );
add_image_size( 'news-medium-mobile', 354, 270, true );

add_image_size( 'news-small', 142, 110, true );
add_image_size( 'news-small-mobile', 354, 270, true );

For integrating with other plugins, you also need to add these images to the image_size_names_choose filter.

<?php
/**
 * Registers the above image sizes for extended useage. (eg manual-image-crop plugin)  
 *
 * @author Oran Blackwell
 */
 
add_filter( 'image_size_names_choose', 'responsivized_image_sizes' );
function responsivized_image_sizes( $sizes ) {
	return array_merge(
		$sizes,
		array(
			'news-lead'          => __( 'News Lead Article' ),
			'news-lead-mobile'   => __( 'News Lead for mobile (Features) Article' ),
			
			'news-medium'        => __( 'News Medium (Default) Article' ),
			'news-medium-mobile' => __( 'News Medium for mobile (Features) Article' ),
			
			'news-small'         => __( 'News Small (Features) Article' ),
			'news-small-mobile'  => __( 'News Small for mobile (Features) Article' )
		)
	);
}
/**
 *
 * @param     string $id post_id
 * @param     string  $desired_size name used in add_image_size()
 * @return    string HTML
 * @global    $_wp_additional_image_sizes
 *
 * @uses      http://wordpress.org/plugins/mobble/
 * @author    Oran Blackwell
 * @version   1.0.0
 *
 * @todo Add better checking for the existence of images - including default.
 
 * @example <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
 *   <?php responsivized_image( get_the_ID(), 'news-lead' );  ?>
 * </a>
 * 
 */
function responsivized_image( $id, $desired_size = 'news-small' ) {
	global $_wp_additional_image_sizes;
	$s = ( is_mobile() ? $desired_size . '-mobile' : $desired_size );
	$w = $_wp_additional_image_sizes[ $s ]['width'];
	$h = $_wp_additional_image_sizes[ $s ]['height'];
	if ( has_post_thumbnail( $id, $s ) ) {
		get_the_post_thumbnail( $s, array( 'class' => $s, 'alt' => get_the_title( $id ) ) );
	} else {
		return '<img src="http://placehold.it/' . $w . 'x' . $h . '" alt="no image"
				class="' . $s . '" width="' . $w . '" height="' . $h . '"/>';
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment