Definition:
function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {}
Get an HTML img element representing an image attachment
While $size will accept an array, it is better to register a size with add_image_size() so that a cropped version is generated. It’s much more efficient than having to find the closest-sized image and then having the browser scale down the image.
Parameters
- int $attachment_id: Image attachment ID.
- string $size: Optional, default is ‘thumbnail’.
- bool $icon: Optional, default is false. Whether it is an icon.
- $attr
Return values
returns:HTML img element or empty string on failure.
Defined filters
- wp_get_attachment_image_attributes
apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment )
Source code
function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') { $html = ''; $image = wp_get_attachment_image_src($attachment_id, $size, $icon); if ( $image ) { list($src, $width, $height) = $image; $hwstring = image_hwstring($width, $height); if ( is_array($size) ) $size = join('x', $size); $attachment =& get_post($attachment_id); $default_attr = array( 'src' => $src, 'class' => "attachment-$size", 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first 'title' => trim(strip_tags( $attachment->post_title )), ); if ( empty($default_attr['alt']) ) $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption if ( empty($default_attr['alt']) ) $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title $attr = wp_parse_args($attr, $default_attr); $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment ); $attr = array_map( 'esc_attr', $attr ); $html = rtrim("<img $hwstring"); foreach ( $attr as $name => $value ) { $html .= " $name=" . '"' . $value . '"'; } $html .= ' />'; } return $html; }
3681
No comments yet... Be the first to leave a reply!