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

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

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自定义翻页分页代码

请先登录后,再发表评论 ~ ~
发表评论
评论 (0)

发表帖子
广告位招租( ¥5 / 天 )
点击咨询
最新帖子

南国老符
2025-05-26 16:54
南国老符
2024-09-29 10:29
南国老符
2023-12-15 21:41
广告位招租( ¥5 / 天 )
点击咨询
最近评论

U
user1379
回复:版本号多少?
U
user1379
回复:新版本修复了,下载新版本即可
U
user1379
U
user1304
回复:默认没有这个功能,你可以自行二次开发后期可能会考虑在站群版本上加入此功能及商城功能
Y
yuanis90
回复:后台->语言->全局管理->模型管理->编辑->启用关键词内链即可
Y
yuanis90
回复:后台已经启用了,但是前台产品说明的关分键词还是没有自动链接到,
购买VIP
购买授权
余额充值
发表帖子
客服微信