Get image URL from post in wordpress

To get the image URL of post thumbnail in wordpress is little difficult because the wordpress doesn’t provide any function to get the image URL. It only returns the full HTML code of image.

We get the image URL from the Thumbnail ID and the Thumbnail ID we will get from the POST ID.

To get the single post attachment url use the following code

$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id($mypost->ID), 'large-thumb' ); // returns an array
$timage[]=$image_attributes[0];
Here is the large-thumb is the thumbnail name that could be large, medium or which is defined in function.
You can use this code in a loop to get more than 1 post attachment url

Get attachment url in Loop

<?php
global $post;
$args = array( 'numberposts' => 3, 'offset'=> 0, 'category' => '4' );
$myposts = get_posts( $args );
	foreach( $myposts as $post ) :	setup_postdata($post);

		$url[] = get_permalink();
//echo wp_get_attachment_image( $attachment->ID, 'full' );
		$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id($mypost->ID), 'large-thumb' ); // returns an array
		$timage[]=$image_attributes[0];
		$timage_attributes = wp_get_attachment_image_src( get_post_thumbnail_id($mypost->ID), 'full'  ); // returns an array
		$limage[]=$timage_attributes[0];

	endforeach; wp_reset_query(); ?>


To seek challenging roles and to achieve excellence in the field of Open Source Web Technology with a profound spirit of commitment and dedication.

Share This Post

Related Articles

© 2017 Sumit Bansal. All rights reserved. Site Admin · Entries RSS · Comments RSS
Powered by WordPress · Designed by Theme Junkie