从wordpress帖子获取第一张图片

时间:2013-08-31 05:40:36

标签: php wordpress

使用以下代码我可以打印标题,发布日期。现在我想从我的帖子内容得到第一张图片我怎么能解决这个问题。我也尝试了the_date(),the_title()来显示日期和时间但是徒劳无功。提前致谢。

    $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++;
}
?>

2 个答案:

答案 0 :(得分:0)

您可以尝试此代码

 <?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;
?>

答案 1 :(得分:0)

以下是获取WordPres帖子第一张图片的演示代码:

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

要显示帖子的第一张图片,请在循环中使用以下代码:

<?php echo get_first_image(); ?>

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