Skip to content

Instantly share code, notes, and snippets.

@scofennell
Created May 23, 2014 01:00
Show Gist options
  • Save scofennell/1a8662371a7dc350f977 to your computer and use it in GitHub Desktop.
Save scofennell/1a8662371a7dc350f977 to your computer and use it in GitHub Desktop.
WordPres function to detect if an image is a portrait, by aspect ratio
<?php
/**
* Given an attachment_id and a definition of portraiture, detect if a photo is a portrait
*
* @param int $attachment_id the attachment_id for the image
* @param mixed $max_ratio the aspect ratio that defines portraiture
* @return boolean returns true if image is a portrait, otherwise returns false
*/
function sjf_deh_is_portrait( $attachment_id, $max_ratio='.67' ){
// if the attachment id is not an int, bail
if( !is_int( $attachment_id ) ) { return false; }
// if the max ratio is not a float or an int, bail
if( !is_numeric( $max_ratio ) ) { return false; }
// get the width height of the image
$att_src_array = wp_get_attachment_image_src( $attachment_id, 'full' );
if( !is_array( $att_src_array ) ) { return false; }
$width = $att_src_array[1];
$height = $att_src_array[2];
// given a height and a max aspect ratio, the threshold_width is the maximum width the image can be, and still be a portrait
$threshold_width = $max_ratio * $height;
// if the image is narrower than the threshold width, it's a portrait
if( $width < $threshold_width ) { return true; }
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment