wordpress调用文章第一张图做缩略图功能,代码如下:
/**
* 调用文章缩略图 开始
* @author albert
* @date 2021-06-08
*/
// step1:开启缩略图功能
if ( function_exists('add_theme_support') ) add_theme_support('post-thumbnails');
// step2:获取文章第一张图片
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个随机图片
$random = 'nopic';
$first_img = get_bloginfo ( 'stylesheet_directory' ).'/assets/albert/img/'.$random.'.png'; //默认图片路径在主题目录下的/images/random/目录里
}
return $first_img; //返回图片地址
};
// step3:在需要调用文章图片的主题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().'">';
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().'" />';
}
echo '</a>';
endwhile; //结束while循环
wp_reset_query(); //结束query_posts查询
*/
/**
* 调用文章缩略图 结束
* @author albert
* @date 2021-06-08
*/上一篇: wordpress分类列表页去掉“分类”字样的代码
下一篇: wordpress自定义翻页分页代码