0

使用以下代码,我可以打印标题、发布日期。现在我想从我的帖子内容中获取第一张图片我该如何解决这个问题。我还尝试了 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++;
}
?>
4

2 回答 2

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;
?>
于 2013-08-31T05:46:20.530 回答
0

这是获取 WordPress 帖子的第一张图片的演示代码:

// 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(); ?>

来源:获取 WordPress 帖子的第一张图片并将其设置为特色图片

于 2017-04-20T13:11:22.743 回答