Get images from post content in wordpress

When you want to display content of a post in wordpress, you can use just “the_content” in the loop to display content. Now there are some scenarios where you want to display only images of the post instead of text. So here in this post I will tell you that how we can get images from post content in wordpress. This is not very difficult task we add some code in wordpress loop and get what we want. So just paste following code in your wordpress “page.php” , “single.php” or your custom php file.

 

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>

	<?php
	$postdata = $post->post_content;
	$searchtag ='~<img [^\>]*\ />~'; 

	// get all the images and save them in $postimages
	preg_match_all( $searchtag, $postdata, $postimages );

	// Check to see if we have at least 1 image
	$totalimages = count($postimages[0]);

	if ( $totalimages > 0 ) {
	     // Now you can add here what you want to do with those images.
	     // i just display all images.

	     for ( $i=0; $i < $totalimages ; $i++ ) {
	          echo $postimages[0][$i];
	     };
	};

	endwhile;
	endif;
	?>

So that is all. you can get post images using this code. feel free to ask any question in the comment section below.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.