Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp get attachment url


Returns a full URI for an attachment file or false on failure.


<?php wp_get_attachment_url$id ); ?>


(integer) (required) The ID of the desired attachment
Default: None

Return Value

Returns URI to uploaded attachment or "false" on failure.

Default Usage

<?php echo wp_get_attachment_url( 12 ); ?> 

Outputs something like http://example.net/wp-content/uploads/filename


Use Post Thumbnail as 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>';


You can change the output of this function through the wp get attachment url filter.

This function will not urlencode the url. If you have attachments with invalid characters in their name, you should rawurlencode the ouput of this function in order to have a valid url.

Sample code that gives you a root relative url to your attachment:

$parsed = parse_url( wp_get_attachment_url( $attachment->ID ) );
$url    = dirname( $parsed [ 'path' ] ) . '/' . rawurlencode( basename( $parsed[ 'path' ] ) );

If you want a URI for the attachment page, not the attachment file itself, you can use get_attachment_link.

Also refer: wp_insert_attachment, wp_upload_dir, wp_get_attachment_image_src

Change Log

Since: 2.1.0

Source File

wp_get_attachment_url() is located in wp-includes/post.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()

See also index of Function Reference and index of Template Tags.