Created
October 30, 2017 17:01
-
-
Save ginsterbusch/fc362b2c5ff720be0feb70d2d6665f48 to your computer and use it in GitHub Desktop.
Retrieve appropriate image size in WordPress (eg. when moving from TimThumb to regular WP sizes).
This file contains 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 | |
/** | |
* @author Fabian Wolf | |
* @link http://usability-idealist.de/ | |
* @license GNU GPL v2 or later | |
*/ | |
// try fetching an appropriate size setting based on width, optionally on height, too | |
if( !empty( $width ) ) { | |
// fetch available sizes | |
$arrImageSizes = $this->get_image_sizes(); | |
// retrieve anything with the width <= current width | |
foreach( $arrImageSizes as $strSize => $arrSizeAtts ) { | |
if( $arrSizeAtts['width'] <= $width ) { | |
$arrPossibleSizes[ $strSize ] = $arrSizeAtts; | |
$arrWidths[ $strSize ] = $arrSizeAtts[ 'width']; | |
if( !empty( $height ) && $arrSizeAtts['height'] > $height ) { | |
unset( $arrPossibleSizes[ $strSize ] ); | |
unset( $arrWidths[ $strSize ] ); | |
} | |
} | |
} | |
if( !empty( $arrPossibleSizes ) ) { | |
// sort widths | |
natsort( $arrWidths ); | |
$arrRWidths = array_reverse( $arrWidths, true ); | |
$c = 0; | |
$strAppropiateSize = ''; | |
foreach( $arrRWidths as $strSize => $iWidth ) { | |
if( $c == 0 ) { | |
$strAppropiateSize = $strSize; | |
break; | |
} | |
$c++; | |
} | |
// eg. width = 200, height = 150 .. | |
if( !empty( $strAppropiateSize ) ) { | |
$atts['size'] = $strAppropiateSize; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: This is just a snippet out of some actual work I'm doing right now. Didnt want it to go under though. Its supposed to be used in a backward compatiblity hack for the WP gallery shortcode (
gallery_shortcode()
).