wp_get_attachment_image_src()
Gets an array of data for the specified image: URL, width, height of the attachment image.
Note: use the first (zero) element of the array for the src
attribute.
Use wp_get_attachment_image_url() when you need to get ready attachment URL.
Hooks from the function
Return
Array|false
. An array containing the following data:
[0] => url [1] => width [2] => height [3] => is_intermediate
Usage
wp_get_attachment_image_src( $attachment_id, $size, $icon );
- $attachment_id(number) (required)
- The ID of the attachment image whose data you want to retrieve.
- $size(string/array)
The size of the image whose data you want to retrieve. In this parameter you can specify the size provided in WordPress
thumbnail
,medium
,large
,full
or any other registered size.You can also specify a size as an array in the form of two elements (width, height):
array( 32, 32 )
. In this case the most suitable size will be chosen and then the image will be shrunk/stretched to that size.Since version 2.5 this parameter does not affect the size of media icons (icons for files), they are always shown in their original size.
Default: 'thumbnail'
- $icon(true/false)
- Set to true (1) to show media icons for non-image attachments (.zip, .rar, etc.)
Default: false
Examples
#1 Default usage
Let's output the html code of the attachment image with ID=8:
<?php $attachment_id = 8; $image_attributes = wp_get_attachment_image_src( $attachment_id ); // array returned ?> <img src="<?php echo $image_attributes[0] ?>" width="<?php echo $image_attributes[1] ?>" height="<?php echo $image_attributes[2] ?>">
#2 Changing the icon directory
In WordPress, special icons are used to show images for attached files (not pictures). For such display is responsible parameter $icon
. So, for image attachments it's image is displayed, but for other files is displayed an icon corresponding to its type. For example, for a .mp3
file will be shown the image audio.jpg
from the wp-includes/images/crystal/
folder.
This example shows how to change the section where the media icons will come from. Let's change the default directory to the theme folder: wp-content/themes/yourtheme/images
(of course, this folder should contain images for different file types).
add_filter( 'icon_dir', 'my_theme_icon_dyrectory' ); function my_theme_icon_dyrectory( $icon_dir ) { return TEMPLATEPATH . '/images'; } add_filter( 'icon_dir_uri', 'my_theme_icon_uri' ); function my_theme_icon_uri( $icon_dir ) { return get_bloginfo( 'stylesheet_directory' ) . '/images'; }
This code can be placed to the functions.php theme file
Changelog
Since 2.5.0 | Introduced. |