How To Get Images From WordPress Content Or WordPress Post

Hi Friends, In this post I am going to write about getting images from wordpress post content, I want this because I want to show post content without images on home page for one of my client, So below is code by which we can get all images one by one from content of post.

// Start the Loop
<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
<?php
// Set the post content to a variable
$temppostcontent = $post->post_content;

// Define the pattern to search
$temppattern = '~<img alt="" />]*\ />~';

// Run preg_match_all to grab all the images and save the results in $resultpics
preg_match_all( $temppattern, $temppostcontent, $resultpics );

// Count the results
 $iNumberOfPics = count($resultpics[0]);

// Check to see if we have at least 1 image
if ( $iNumberOfPics > 0 )
{

     // Now here you would do whatever you need to do with the images
     // For this example I'm just going to echo them
     for ( $i=0; $i < $iNumberOfPics ; $i++ )
     {
          echo $resultpics[0][$i];
     };

};

// ...finish the loop, etc</pre>

So above is code to get images from post content. 2nd Line of this code is starting if condition to check posts is available or not and then if posts available starts while loop. In 6th line we take value of post content in one variable ‘$temppostcontent’ everytime while loop runs.In 9th line we define patter of tag as regular expression to search from post content.Now in 12th line we use preg_match_all to grab all the images and save the results in $resultpics and after that we get array of images from post in $resultpics variable, So we run for loop for $resultpics to get pictures in image. So by this way we can get images from post.

I hope this post helpful for someone. If you have any question then you can ask me anytime or post it in comment.

Also I am WordPress Developer, Freelance PHP Developer having more than 3 years of experience, So if you want to do any projects then you can contact me.

Hostgator Hosting in 1 Cent Coupon Code – “1CENTHECOUPON” (Without Quotes).