Saturday, March 31, 2012

WordPress : Find image sizes from filname/URL

This function is a small hack to scan the upload directory for an image matching certain sizes. The search based on the image names and wordpress nameconvention (xxxxxx-300x200.jpg)

The whole point of this, is you can use this outside the wordpress "loop".

The function uses 3 arguments, third one is optional.
1. $fpath - complete filepath to "original image"
2. $minSizes - array of minimum width/height
3. $maxSizes [optional] - array of maximum width/height

Put following in your themes functions.php

 
function findImageSize($fpath, $minSizes = array(1,1), $maxSizes = array(9999,9999) ){
 $res = false;
 $bs = basename($fpath, ".jpg");
 
 $uploadDir = "wp-content/uploads/";
 $siteUrl = site_url('/');
 $results = glob("{".$uploadDir.$bs."-*x*.jpg"."}",GLOB_BRACE);
 
 $smallest = array(9999,9999);
 
 foreach ($results as $v) {
  $bst = basename($v, ".jpg");
  $ldi = strrpos($bst,"-");
  
  if($ldi === false){
  }else {
   $tmp = substr($bst,$ldi+1); $wihe = split("x",$tmp); $iw = intval($wihe[0]); $ih = intval($wihe[1]);
   if($iw < $minSizes[0]){;} else if ($iw > $maxSizes[0]){;} else if($ih < $minSizes[1]){;} else if($ih > $maxSizes[1]){;} else { 
    if( ($iw*$ih) < ($smallest[0]*$smallest[1]) ){
     $smallest[0] = $iw;
     $smallest[1] = $ih;
     $res = array ('url' => ($siteUrl.$v), 'width' => $iw,'height' => $ih);
     }
    
    }
   }
  }
 
 
 return $res;
 }
 

// Example
$res = findImageSize("http://myblog.com/wp-content/uploads/my-poster-image.jpg", array(300,600) ,array(1024,1024) );
echo $res[url];
echo $res[width];
echo $res[height]; 

No comments:

Post a Comment