WordPress: How to get display all images from a page/post

By Ufuk Erdogmus 9 years ago
Home  /  WordPress  /  WordPress: How to get display all images from a page/post

In a recent custom WordPress development project, we needed a small function to get all the images within posts/pages. Not only uploaded and attached images but also the ones coming from external URL’s as well.

Below is the function to grab the images and the shortcode to print the images within the given post or page. To use it, copy paste the below shortcode in your theme’s functions.php and place the shortcode in your page/post content.

/* Shortcode to print images in a given page */
/*Example shortcode: [weptile-post-images id=90] */
add_shortcode('weptile-post-images','get_images_by_post_id');


/* function to get the images within a given post/page */
function get_images_by_post_id($atts) { 
    if(isset($atts['id'])):
           $pid = $atts['id'];
    else:
           echo 'ID not specified';
    endif;
	$post = get_post( $pid );
	$content = $post->post_content;
	$regex = '/src="([^"]*)"/';
	preg_match_all( $regex, $content, $matches );
	foreach($matches as $image):
	    echo '<img src="'.$image.'" alt="'.$post->post_title.'" title="'.$post->post_title.'">';
	endforeach;
}

 

Category:
  WordPress
this post was shared 0 times
 100