How to get the URL of an attachment as used in the post (6 posts)

  1. matthewbe
    Posted 3 years ago #


    I can't figure out how to get the real images URLs from a post. Below is the function I use to get the URLs of the images from a specific post.

    private function get_images($post_id) {
    	$images = array();
    	$argsThumb = array(
    		'order'          => 'ASC',
    		'post_type'      => 'attachment',
    		'post_parent'    => $post_id,
    		'post_mime_type' => 'image',
    		'post_status'    => NULL
    	$attachments = get_posts( $argsThumb );
    	if ( $attachments ) {
    		foreach ( $attachments as $attachment ) {
    			log_me( wp_get_attachment_url( $attachment->ID ) );
    			log_me( $attachment->post_title );
    			log_me( $attachment->post_name );
    			log_me( print_r( $attachment, true ) );
    			$images[] = wp_get_attachment_url( $attachment->ID );
    	return $images;

    This code works great, but it doesn't give the real URL of the images in the post. E.g. in the post there is an image with URL http://localhost/blog/wp-content/uploads/2013/04/example-300x183.jpg

    Unfortunately, the function above will only return http://localhost/blog/wp-content/uploads/2013/04/example.jpg

    Anyone has an idea how to get *the actual images* used in a specific post?

    Thank you

  2. David Choi
    Posted 3 years ago #

    You can retrieve the image by size paramter using get_the_post_thumbnail() function

    <?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>

    Reference: http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail

  3. matthewbe
    Posted 3 years ago #

    Sure, but how to get the size as used in the post ? That's the question.

  4. David Choi
    Posted 3 years ago #

    You mean the actual image HTML code you have inserted in the content regardless if that image has "attached image" with WP post?

  5. David Choi
    Posted 3 years ago #

    To extract image URL from the content, you have to use regular expressions:


  6. matthewbe
    Posted 3 years ago #

    Thanks, I wrote a blog post about the question:
    Get Attachment Images Of Same Size

Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.