This page redirects to an external site: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/
Languages: English • Italiano • Reference/wp get attachment image 日本語 (Add your language)
Returns an HTML image element representing an attachment file, if there is any, otherwise an empty string.
<?php wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); ?>
<?php echo wp_get_attachment_image( 1 ); ?>
If the attachment is an image, the function returns an image at the specified size. For other attachments, the function returns a media icon if the $icon parameter is set to true.
To get attachment IDs dynamically in a template, you can use get_posts('post_type=attachment'), etc.
Instead of using an array which requires checking all of the image sizes, you should consider registering 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.
$default_attr = array( 'src' => $src, 'class' => "attachment-$size", 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), );
The $attr argument is merged with WordPress's default attributes and passed through the wp_get_attachment_image_attributes filter.
To display all of the images and titles attached to a certain page and display them as a list of bullets you can use the following:
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'full' );
echo '<p>';
echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
}
endwhile; endif; ?>
</ul>
an HTML img element or empty string on failure.
Since: 2.5.0
wp_get_attachment_image() is located in wp-includes/media.php.
Attachment Functions:
get_children(), get attached media(), the_attachment_link(), get_attachment_link(), wp_get_attachment_link(), wp_get_attachment_image(), wp_get_attachment_image_src(), wp_get_attachment_url(), wp_get_attachment_thumb_file(), wp_get_attachment_thumb_url(), is_attachment(), wp_get_attachment_metadata()