第一:主要是在function里面加入以下代码,然后调用。
function catch_that_image() {
global $post, $posts;$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
//获取文章中第一张图片的路径并输出
$first_img = $matches [1] [0];
//如果文章无图片,获取自定义图片
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
//请自行设置一张default.jpg图片
}
return $first_img;
}
然后在前端输出
<?php catch_that_image();?>
第二:循环调用分类目录和文章内的第一张图片。
<?php function catch_that_image() {
global $post, $posts;
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "http://localhost/default.jpg";
}
return $first_img;
}
$cats = get_categories();
foreach ( $cats as $cat ) {
query_posts( 'showposts=8&cat=' . $cat->cat_ID );
?>
<div class="vl-double-small-block">
<h2 class="vl-block-title" style="width:799px"><?php echo $cat->cat_name; //栏目标题 ?></h2>
<div class="vl-double-small-block">
<?php while ( have_posts() ) { the_post(); global $post; ?>
<div class="vl-post-item vl-clearfix">
<div class="vl-post-thumb">
<a href="<?php the_permalink();//图片链接地址?>">
<img alt="<?php the_title();//图片的alt值;?>" src="<?php echo catch_that_image(); //第一张图片 ?>" width="104px">
</a>
</div>
<div class="vl-post-content">
<h3><a href="<?php the_permalink(); //文章链接 ?>"><?php the_title(); //文章标题 ?></a></h3>
<div class="posted-on">
<i class="fa fa-clock-o" aria-hidden="true"></i>
<time class="entry-date published" datetime="<?php echo date('d M, Y',strtotime($post->post_modified)); //日期格式化显示 ?>">
</time>
<span class="byline">By<span class="author vcard"><?php the_author() //作者 ?></span></span>
</div>
<?php } wp_reset_query(); ?>
</div>
<?php } ?>