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

阅读: 评论:0

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

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 = "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 } ?>

本文发布于:2024-01-30 19:47:31,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170661525222399.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:第一张   文章   图片   wordpress
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23