How to Use the wp_get_attachment_image Function in WordPress

Last Updated on July 3, 2023 by Mike Kipruto

The wp_get_attachment_image is a WordPress function that gets an HTML img element representing an image attachment. It allows one to easily retrieve and display image attachments based on their IDs.

PHP
wp_get_attachment_image( int $attachment_id, string|int[] $size = 'medium', bool $icon = false, string|array $attr = '' );

The wp_get_attachment_image() function typically requires the attachment_id as a parameter. This ID serves as a unique identifier for the image, allowing the function to retrieve and display the desired image.

This function takes the following parameters:

  1. $attachment_id (int): This is a required parameter that specifies the attachment ID of the image you want to retrieve. The attachment ID uniquely identifies an image in the WordPress media library.
  2. $size (string|int[]): This parameter determines the size of the image to be displayed. It can be specifiedas a string representing a registered image size (e.g., ‘thumbnail’, ‘medium’, ‘large’), or as an array containing the width and height values in pixels (e.g., array(500, 300)). If no size is specified, it defaults to ‘thumbnail’.
  3. $icon (bool): This parameter determines whether to display the image as an icon. If set to true, it will attempt to display the attachment file as an icon. By default, it is set to false.
  4. $attr (string|array): This parameter allows you to add additional attributes to the HTML image element. It can be specified as a string containing a space-separated list of attributes, or as an associative array of attribute-value pairs.

Usage Example

#1 Outputing a ready-to-use HTML image

To display the medium size image (<img> tag) of the attached file with ID 30:

PHP
<?php echo wp_get_attachment_image( 30, 'medium'); ?>

This outputs something like this HTML:

HTML
<img width="300" height="300" 
    src="http://example.com/wp-content/uploads/2023/05/3-300x300.jpg" 
    class="attachment-medium size-medium" 
    alt="Text from Alt Text field"
/>

The alt text will be filled in only if it is specified for the attachment in the special field (alt text). The alt does not include the text from the title, description or caption of the image.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *