为wordpress文章添加缩略图,wordpress自动获取文章内图片为特色图像

[ wordpress教程   // 2014-12-11  ]
为wordpress文章添加缩略图,wordpress自动获取文章内图片为特色图像
325

WordPress:为文章设置默认的特色图像(Default featured image)的方法很多,各有优劣,选择哪种方式要看自己的用途,有些方法并没有真的设置了特色图像,但用起来却很灵活。

缩略图可以来自featured图片,也可以来自文章内图片,还可以在前两者均无时随机显示一些图片,接下来就介绍如何修改主题模板实现为wordpress文章自动抓取文章缩略图的功能。

wordpress自动抓取文章缩略图(特色图像)的功能:

1、添加功能函数

找到使用的主题模板的functions.php文件在之间添加如下代码:

if ( function_exists('add_theme_support') ) add_theme_support('post-thumbnails'); function catch_first_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)){ $random = mt_rand(1, 20); echo get_bloginfo ( 'stylesheet_directory' ); echo '/images/random/tb'.$random.'.jpg'; } return $first_img; }

请在主题目录images文件夹下建立random文件夹,里面存入20张图片,命名tb1-20,jpg格式

2、指定位置调用函数

找到index.php文件即首页文件,找到the_content();或相似的代码在它之前添加如下代码:

<img class="home-thumb" src="<?php echo catch_first_image() ?>" width="140px" height="100px" alt="<?php the_title(); ?>" />

3、添加缩略图样式CSS代码:

具体样式需要根据网站内容调整,如下作为示例

home-thumb{margin:5px 15px 5px 5px;width:140px;height:100px;border:3px solid #eee; float:left;overflow:hidden;} .home-thumb img{max-height:186px;max-width:186px}