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.  
  9. if(empty($first_img)){ //定义默认图片
  10. $first_img = "/images/default.jpg"; //默认图片地址需自己设置
  11. }
  12. return $first_img;
  13. }

在需要调用到文章第一张的地方调用该函数:

  1. <?php echo catch_that_image() ?>