wp_get_attachment_url

Definition:
function wp_get_attachment_url( $post_id = 0 ) {}

Retrieve the URL for an attachment.

Parameters

  • int $post_id: Attachment ID.

Defined filters

  • wp_get_attachment_url
    apply_filters( 'wp_get_attachment_url', $url, $post->ID )

Source code

function wp_get_attachment_url( $post_id = 0 ) {

	$post_id = (int) $post_id;

	if ( !$post =& get_post( $post_id ) )

		return false;



	if ( 'attachment' != $post->post_type )

		return false;



	$url = '';

	if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file

		if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory

			if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location

				$url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location

			elseif ( false !== strpos($file, 'wp-content/uploads') )

				$url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );

			else

				$url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.

		}

	}



	if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this.

		$url = get_the_guid( $post->ID );



	$url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );



	if ( empty( $url ) )

		return false;



	return $url;

}

3693

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: