Loading
0

wordpress主题开发在首页调用文章图片

开发WordPress主题时都需要调用文章图片作为首页图片展示,wordpress主题开发在首页调用文章图片时,我们要先对它进行判断,如果缩略图存在就调用缩略图;如果缩略图不存在,就调用文章内容中的第一张图片;如果缩略图和文章内容第一张图片都不存在,就调用wordpress主题自带的默认图片。

wordpress主题开发在首页调用文章图片

第一步:在wordpress主题的functions.php文件开启缩略图功能

if ( function_exists('add_theme_support') ) add_theme_support('post-thumbnails'); //开启缩略图

第二步:在wordpress主题的functions.php文件中添加获取文章第一张图片的方法:

function catch_first_image() {

global $post; $first_img = '';

ob_start(); //打开输出缓冲

ob_end_clean(); //清空缓冲区 并关闭输出缓冲

//通过正则来匹配文章内容中的图片,把获取到的图片地址放到$matches数组中

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

$first_img = $matches [1] [0]; //从数组中获取第一张图片地址

if(empty($first_img)){ //如果没有图片,就启用默认随机图片

$random = mt_rand(1, 10); //随机 1-10 的数字,表示共10个随机图片

$first_img = get_bloginfo ( 'stylesheet_directory' ).'/images/random/'.$random.'.jpg'; //默认图片路径在主题目录下的/images/random/目录里

}

return $first_img; //返回图片地址

};

第三步:在需要调用文章图片的wordpress主题php文件(如首页)中添加如下代码:

query_posts('posts_per_page=4&caller_get_posts=1&orderby=comment_count&cat=2'); //查询指定分类id=2下的文章4篇

while (have_posts()) : the_post(); //循环调用

echo '<a target="_blank" href="'.get_permalink().'" class="title" title="'.$post->post_title.'">';

if (has_post_thumbnail()) { //如果缩略图存在,就调用缩略图

the_post_thumbnail( 'thumbnail',array( 'alt' => trim(strip_tags( $post->post_title )), 'class' => 'home-thumb'));

}else { //如果缩略图不存在,就调用functions.php中的catch_first_image()方法获取第一张图或默认图

echo '<img src="'.catch_first_image().'" alt="'.$post->post_title.'" width="150" height="150" />';

}

echo '</a>';

endwhile; //结束while循环

wp_reset_query(); //结束query_posts查询