简体   繁体   中英

get first image from wordpress post

using the following code i can print title,date of post. now i would like to get the first picture form my post content how can i tackle this.i also tried the_date() ,the_title(), to display date and time but in vain . Thanks in advanced.

    $args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'date' );
$postslist = get_posts( $args );


$postcound=0;
foreach ($postslist as $post) {
echo "date".$postslist[$postcound]->post_date;
 echo "<br />title:".$postslist[$postcound]->post_title;
  echo "<br />content:".$postslist[$postcound]->post_content;



echo "<br />id:". $postslist[$postcound]->ID;
$postcound++;
}
?>

You can try this code

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

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

// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

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

if ( $iNumberOfPics > 0 ) {
   // Now here you would do whatever you need to do with the images
   // For this example the images are just displayed
   for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
        echo $aPics[0][$i];
   };
};

endwhile;
endif;
?>

Here is the demo code to get the first image of a WordPres post:

// Get first image
function get_first_image() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_image = $matches [1] [0];
if(empty($first_image)){ //Defines a default image
// Set the default image if there are no image available inside post content
$first_image = "/img/default.jpg";
}
return $first_image;
}
// End Get First Image

To display the first image of the post use the below code inside the loop:

<?php echo get_first_image(); ?>

Source: Get first image of WordPress post and set it as featured image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM