Nov 19, 2014

Posted in , , , ,

Wordpress 4.0 Hosting Tutorial - Getting Images From WordPress Content Or WordPress Post

During this article I'm heading to write down about how to getting images from Wordpress post content or Wordpress post. I need to do this because I need to show post content material while not images on home page for one among my client. So, this is the code by which we could get all images one by one from content of post.
France Wordpress 4.0 Hosting

// 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>

The code on above is to get images from post content. 2nd Line of the code is starting in case situation to examine posts is available or otherwise then in case posts accessible starts while loop. In 6th line we consider value of post content in one variable ‘$temppostcontent’ everytime when loop runs. In 9th line we determine patter of How To Get Images From Wordpress Content Or Wordpress Post tag as regular expression to look from post content. Currently in 12th line we use preg_match_all to get all of the images and use results in $resultpics and after that many of us get array of images from post in $resultpics variable, Thus we run for loop for $resultpics to get pictures in image. Thus by in this way we could get images from post.

0 comments:

Post a Comment

thanks for your comment!