Set custom sizes (beyond the $size argument) to WordPress Feature Image/thumbnail

Set custom sizes (beyond the $size argument) to WordPress Feature Image/thumbnail

get_the_post_thumbnail() is a very useful WordPress function, but I tried to cheat and set up an image of a X size to then resize it to half the size so that it would look good on Retina displays.

Shame get_the-post_thumbnail() returns the full <img> tag rather than just a URI, so I tried to pass some arguments, like class but also width and height, likeso

$args = array(	'class'	=> "desktopOnly", 'width => '240', 'height' => '444', alt'	=> trim( strip_tags( $concert["post_title"] ) ));
								
$photo =  get_the_post_thumbnail($concert["ID"], "concert-listing", $args ) ;

Shame that my height and width attributes were ignored, so I thought I could do with some preg_match action!

if(has_post_thumbnail( $concert["ID"] )):
	$args = array(	'class'	=> "desktopOnly", 'alt'	=> trim( strip_tags( $concert["post_title"] ) ));
	$photo =  get_the_post_thumbnail($concert["ID"], "concert-listing", $args ) ;

	$replace = array('width' => '240', 'height'=> '444');

	foreach($replace as $item => $size):
		//resize img with regex :S
		$matches = array();
		$pattern = '/('.$item.'=")((\d+))"/';
		preg_match ($pattern, $photo, $matches);

		if(!empty($matches[2])):
			//now replace it
			$photo = str_replace($item.'="'.$matches[2].'"', $item.'="'.$size.'"', $photo);
		endif;
	endforeach;

	echo $photo;
endif;

Enjoy 🙂

No Comments

Post A Comment