WordPress调用文中第一张图片为缩略图。经常看到很多WordPress主题调用文中的第一张图片为缩略图,感觉不错,现记录如下。
WordPress调用文中第一张图片为缩略图
将以下代码添加到你的主题模板的function.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)){ //如果文中无图时设置默认缩略图
- $site_url = bloginfo('template_url');
- $first_img ="$site_url/xx/thumbnail.png";
- }
- return $first_img;
- }
如果文中无图时,则不调用图片为缩略图代码则为
- 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];
- //这里干掉了默认图片。
- return $first_img;
- }
把以下代码添加到你想要显示图片的位置,即可实现自动调用文章中第一张图片
- <img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" /></a>
可以在CSS里根据自己主题添加缩图图样式,具体视自己习惯而定
本文参考了http://www.uedbox.com/wordpress-calls-the-first-picture/一文,有修改。