检索面向“横向”图像的函数
function wpse_96012_landscape_image() {
/* global post object holding info about the current post */
global $post;
/* grab all images attached to the current post */
$attached_images = get_children( array(
\'post_parent\' => $post->ID,
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\'
) );
/* set minimum ratio between width / height, change to your liking */
$minimum_aspect_ratio = 1.2;
/*
* iterate over attachments
* get size, compare width & height
* stop execution if an image with "landscape" dimensions is found
*/
foreach( $attached_images as $image ) {
$url = wp_get_attachment_url( $image->ID );
$size = getimagesize( $url );
if ( $size[0] >= ( $size[1] * $minimum_aspect_ratio ) ) {
return $url;
}
}
return false;
}
上述函数将返回第一幅图像的URL,其纵横比大于或等于设置的最小值或
false
如果没有找到。
因此,如果您想在有图像的情况下输出图像,您可以这样做:
$landscape_image_url = wpse_96012_landscape_image();
if ( $landscape_image_url ) {
echo \'<img alt="landscape image" src="\' . $landscape_image_url . \'" />\';
}
参考文献
get_children
(可湿性粉剂)
getimagesize
(PHP)