wordpress调用文章第一张图做缩略图功能

南国老符 南国老符 最后更新于:2021-08-19 浏览:1217

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
 */



点赞 (0)

收藏 (0)
转载请务必注明: 来源:《建站管家》https://www.df81.com/news/214.html

本站部分信息来源网络,如有侵权,请联系QQ:1062129401删除。

上一篇: wordpress分类列表页去掉“分类”字样的代码

下一篇: wordpress自定义翻页分页代码

请先登录后,再发表评论 ~ ~
发表评论
发表帖子
广告位招租( ¥5 / 天 )
点击咨询
最新帖子

南国老符
2025-07-17 17:24
南国老符
2025-07-13 19:36
南国老符
2025-05-26 16:54
南国老符
2024-09-29 10:29
广告位招租( ¥5 / 天 )
点击咨询
最近评论

Y
yuanis90
回复:在后台->全局管理->网站设置->网站html代码,把你申请的分享代码贴到这里保存即可。以后发问题,请贴出具体版本号
南国老符
回复:发表帖子发不了  乱码
南国老符
回复:第一位参与的老总,是做洗衣店saas系统的,需要的请联系
9
9252
回复:新版已经修复了的,升级忘记覆盖了,你重新下载即可。
U
user1304
回复:PHP开启fileinfo扩展即可
U
user1379
回复:版本号多少?
购买VIP
购买授权
余额充值
发表帖子
客服微信