WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. matthewbe
    Member
    Posted 1 year ago #

    Hello,

    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
    Member
    Posted 1 year 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
    Member
    Posted 1 year ago #

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

  4. David Choi
    Member
    Posted 1 year 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
    Member
    Posted 1 year ago #

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

    http://stackoverflow.com/questions/3371902/php-regex-get-image-from-url

  6. matthewbe
    Member
    Posted 1 year 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

Tags

No tags yet.