Running an e-commerce store, or simply a blog that’s heavy on visuals, you’re constantly tasked with the need to handle images dynamically. Suppose you’re developing a feature where product images have to be displayed in various sizes across different sections of your website – the ‘Header’, ‘Product Gallery’, ‘Thumbnail sections’ and so forth. Here’s where the ‘wp_get_attachment_image_src’ function swoops into action. This lean yet incredibly powerful function allows you to swiftly retrieve an image that is representative of an attachment, helping maintain a visually coherent user interface without an overload of images clogging server or consuming unneeded bandwidth.
Syntax
wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) |
Parameters
- $attachment_id (int): Image attachment ID.
- $size (string|array) Optional. Image size. Accepts any registered image size name or an array of width and height values in pixels (in that order). Default value is ‘thumbnail’.
- $icon (bool) Optional. Whether the image should fall back to a mime type icon. Default value is false.
Return Value
The function returns an array or false, depending on whether the attachment has an available source URL.
- Array format:
- Index 0: Image source URL.
- Index 1: Image width in pixels.
- Index 2: Image height in pixels.
- Index 3: Whether the image is a resized image.
How it works
/** | |
* Retrieves an image to represent an attachment. | |
* | |
* @since 2.5.0 | |
* | |
* @param int $attachment_id Image attachment ID. | |
* @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of | |
* width and height values in pixels (in that order). Default 'thumbnail'. | |
* @param bool $icon Optional. Whether the image should fall back to a mime type icon. Default false. | |
* @return array|false { | |
* Array of image data, or boolean false if no image is available. | |
* | |
* @type string $0 Image source URL. | |
* @type int $1 Image width in pixels. | |
* @type int $2 Image height in pixels. | |
* @type bool $3 Whether the image is a resized image. | |
* } | |
*/ | |
function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) { | |
// Get a thumbnail or intermediate image if there is one. | |
$image = image_downsize( $attachment_id, $size ); | |
if ( ! $image ) { | |
$src = false; | |
if ( $icon ) { | |
$src = wp_mime_type_icon( $attachment_id ); | |
if ( $src ) { | |
/** This filter is documented in wp-includes/post.php */ | |
$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' ); | |
$src_file = $icon_dir . '/' . wp_basename( $src ); | |
list( $width, $height ) = wp_getimagesize( $src_file ); | |
} | |
} | |
if ( $src && $width && $height ) { | |
$image = array( $src, $width, $height, false ); | |
} | |
} | |
/** | |
* Filters the attachment image source result. | |
* | |
* @since 4.3.0 | |
* | |
* @param array|false $image { | |
* Array of image data, or boolean false if no image is available. | |
* | |
* @type string $0 Image source URL. | |
* @type int $1 Image width in pixels. | |
* @type int $2 Image height in pixels. | |
* @type bool $3 Whether the image is a resized image. | |
* } | |
* @param int $attachment_id Image attachment ID. | |
* @param string|int[] $size Requested image size. Can be any registered image size name, or | |
* an array of width and height values in pixels (in that order). | |
* @param bool $icon Whether the image should be treated as an icon. | |
*/ | |
return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon ); | |
} |
- The function first attempts to retrieve the image attachment by downsizing it to the specified size using the image_downsize() function.
- If downsizing fails, indicating that no image is available, the function checks if a mime type icon should be used as a fallback by checking the $icon parameter. If $icon is true, it retrieves the corresponding mime type icon using wp_mime_type_icon() for the specified $attachment_id.
- If a mime type icon is successfully retrieved, it gets the file path and captures its dimensions using wp_getimagesize().
- If both the file path and dimensions are obtained from a mime type icon, an array of image data is created with index assignments for source URL, width, height, and resized status.
- Finally, either the downsized image or array of image data is returned based on the success in previous steps. The return is filtered through wp_get_attachment_image_src hook, and the filtered result is returned as the function’s final output.
Note: If no image is available or any of the intermediate steps encounter errors, false will be returned.
Usage
Inside a Plugin
Let’s say you are developing a plugin that adds image captions to posts. You want to display the featured image of each post along with its caption in a custom widget. To achieve this, you can use the wp_get_attachment_image_src function.
<?php | |
/** | |
* Returns the HTML markup for displaying a post's featured image and caption. | |
* | |
* @param int $post_id The ID of the post. | |
* @return string The HTML markup for the featured image and caption. | |
*/ | |
function display_featured_image_with_caption($post_id) | |
{ | |
$attachment_id = get_post_thumbnail_id($post_id); | |
$image_src = wp_get_attachment_image_src($attachment_id, "large"); | |
if ($image_src) { | |
$caption = get_post_meta($attachment_id, "image_caption", true); | |
return esc_html($caption); | |
} | |
return ""; | |
} |
Explanation:
- The display_featured_image_with_caption function accepts the ID of a post as a parameter.
- It uses the get_post_thumbnail_id function to retrieve the attachment ID of the featured image associated with the post.
- The wp_get_attachment_image_src function is then called with the attachment ID and ‘large’ size as arguments to retrieve an array containing information about the image source URL, width, height, and whether it is an intermediate size or not.
- If an image source is found, it retrieves the caption for that image using get_post_meta.
- The function generates HTML markup to display the featured image with its caption.
- The final HTML markup is returned.
To use this function in your plugin, you can hook it to a suitable action or filter, for example:
<?php | |
add_action("widgets_init", "register_custom_widget"); | |
function register_custom_widget() | |
{ | |
// Register and initialize the custom widget | |
require_once "custom-widget.php"; | |
} |
Inside a Theme
Imagine you are developing a WordPress theme for photographers and would like to display a gallery of images on the homepage. You want to retrieve the thumbnail source URL and display it as a hyperlink to the corresponding image gallery page. You can use the wp_get_attachment_image_src function within your theme.
<?php | |
/** | |
* Retrieves and displays a gallery of images on the homepage. | |
*/ | |
function display_homepage_gallery() | |
{ | |
$gallery_images = get_field("homepage_gallery", "option"); | |
if ($gallery_images) { | |
foreach ($gallery_images as $image) { | |
$thumbnail_src = wp_get_attachment_image_src( | |
$image["ID"], | |
"thumbnail" | |
); | |
$full_src = wp_get_attachment_image_src($image["ID"], "full"); | |
echo " " . esc_attr($image["alt"]) . " "; | |
} | |
} | |
} |
Explanation:
- The display_homepage_gallery function fetches an array of gallery images stored in an Advanced Custom Fields (ACF) field named homepage_gallery.
- If there are any gallery images available, it loops through each image and retrieves its thumbnail source URL using wp_get_attachment_image_src with ‘thumbnail’ size as an argument.
- It also retrieves the full-size image source URL for linking purposes.
- The function generates HTML markup to display each image as a clickable thumbnail linked to its corresponding gallery page.
- The gallery is enclosed within a element with the class gallery.
- Finally, the function echoes out the complete HTML markup.
To utilize this functionality in your theme, you can call the display_homepage_gallery function within an appropriate template file, such as front-page.php.
<?php | |
/** | |
* Template Name: Homepage | |
*/ | |
get_header(); | |
// Displaying homepage content | |
display_homepage_gallery(); | |
// Continue with other sections of the homepage | |
get_footer(); |
Make sure to add proper styles for the .gallery class in your theme’s CSS file to achieve the desired layout for the image gallery.