WordPress调用文中第一张图片为缩略图

WordPress调用文中第一张图片为缩略图。经常看到很多WordPress主题调用文中的第一张图片为缩略图,感觉不错,现记录如下。

WordPress调用文中第一张图片为缩略图


将以下代码添加到你的主题模板的function.php文件


Code   ViewPrint



  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)){ //如果文中无图时设置默认缩略图

  9. $site_url = bloginfo('template_url');

  10. $first_img ="$site_url/xx/thumbnail.png";

  11. }

  12. return $first_img;

  13. }



如果文中无图时,则不调用图片为缩略图代码则为


Code   ViewPrint



  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. return $first_img;

  10. }



把以下代码添加到你想要显示图片的位置,即可实现自动调用文章中第一张图片



  1. <img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" /></a>



可以在CSS里根据自己主题添加缩图图样式,具体视自己习惯而定

WordPress调用文中第一张图片为缩略图 post thumnail

本文参考了http://www.uedbox.com/wordpress-calls-the-first-picture/一文,有修改。

评论

此博客中的热门博文

EndNote为参考文献分类显示

如何选择和阅读科技论文

EndNote X8 汉化版

EndNote X8 新功能简介

推荐25个搜索下载电子书籍的好地方