wp_get_attachment_url()
Gets the URL of the attachment by the provided attachment ID. Gets the link to the file.
An attachment refers to any file added to the media library: image, archive, video, etc. It does not matter whether the attachment is attached to a post or not.
The function does not modify/clean the obtained URL. If the attachment has incorrect characters in its name or URL, the URL should be cleaned using rawurlencode(). For example, we get the relative path of the file:
$parsed = parse_url( wp_get_attachment_url( $attachment->ID ) ); $url = dirname( $parsed['path'] ) . '/' . rawurlencode( basename( $parsed['path'] ) );
If you need to get a link to the attachment page, not to the attachment itself, use get_attachment_link().
Hooks from the function
Returns
String|false
. The URL of the attachment or false if the URL could not be obtained.
Usage
wp_get_attachment_url( $attachment_id );
- $attachment_id(number)
- The ID of the attachment whose URL needs to be obtained.
Default: 0 (current post)
Examples
#1 Display the image attached to the post
Let's say we want to display an image attached to post 5. Then first we need to find out the ID of the attachment and then display the image:
// Get the ID of the attachment of post 5 $id = 5; $attachment_image = get_children( array( 'numberposts' => 1, 'post_mime_type' => 'image', 'post_parent' => $id, 'post_type' => 'attachment' ) ); // take the first picture out of the array $attachment_image = array_shift( $attachment_image ); $img = '<img src="' . wp_get_attachment_url( $attachment_image->ID ) . '" alt="" />'; echo $img; // will return: // <img src="http://example.com/wp-content/uploads/2011/07/robots.txt.jpg" alt="" />
#2 Get the link to the attachment
Let's say we added a picture to the media library and it has an ID 55, then we can get a link to that picture this way:
$image_url = wp_get_attachment_url( 55 ); echo $image_url; // Returns: http://example.com/wp-content/uploads/image.png
#3 Post's thumbnail as a background image
if( have_posts() ){ while( have_posts() ){ the_post(); if( has_post_thumbnail() ){ $feat_image_url = wp_get_attachment_url( get_post_thumbnail_id() ); echo '<div style="background-image:url('. $feat_image_url .');"></div>'; } } }
Notes
- Global. String. $pagenow The filename of the current screen.
Changelog
Since 2.1.0 | Introduced. |