wordpress如何提取文章内的第一张图片

第一:主要是在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 } ?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值