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(); ?>

Share This Post

One Response to "Get image URL from post in wordpress"

Post Comment