WordPress 如何自动显示文章第一张图片的方法

WordPress教程 9251

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

WordPress 自动获取文章第一张图片:

  1. 在当前使用的主题模板的functions.php文件<?php和?>之前添加以下代码
        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";
          }
          return $first_img;
        }
  2. 在当前主题模板的index.php文件的内容代码前或后添加以下代码
    <?php echo catch_that_image() ?>

精品推荐: