WordPress 自动提取文章第一张图片作为缩略图

admin wordpress评论630字数 464阅读模式
摘要

很多 WordPress 博客的主题都设计了首页显示文章缩略图,但其中大部分是采用 WordPress 自定义字段实现的(移步WordPress 博客自定义字段实现日志缩略图),这样每次都要手动添加缩略图,显然很麻烦。所以最好的方法便是自动获取,下面博客吧来介绍下 WordPress 自动显示文章第一张图片的方法。

WordPress 自动获取文章第一张图片:
在当前使用的主题模板的functions.php文件中添加以下代码:

  1. function catch_that_image() {  
  2. global $post, $posts;  
  3. $first_img = '';  
  4. ob_start();  
  5. ob_end_clean();  
  6. $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
  7. $first_img = $matches [1] [0]; 
  8. if(empty($first_img)){ //Defines a default image 
  9. $first_img = "/images/default.jpg";  
  10. }  
  11. return $first_img;  
  12. }  

在当前主题模板的index.php文件的内容代码前或后添加以下代码:

  1. <?php echo catch_that_image() ?>  

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2021年9月27日 17:30:36
  • 转载请务必保留本文链接:https://www.58pxe.com/7723.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: