怎么调用随机缩略图? - wordpress开发

给文章一个个的设置缩略图嫌麻烦?试试这个随机缩略图代码,可以显示随机缩略图

给文章一个个的设置缩略图嫌麻烦?试试这个随机缩略图代码,可以显示随机缩略图。

将以下代码添加至主题根目录下的functions.php文件中的<?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))
	{
		$image_size = getimagesize($first_img);
		$image_width = $image_size[0];
	}
	//如果第一张图不存在或过小,则返回随机图片
	if(empty($first_img) || $image_width<50){
		$first_img = '';
		//从2张图中随机选择,可根据自己的图片数量设置
		$random = mt_rand(1, 2);
		echo get_bloginfo ( 'stylesheet_directory' );
		echo '/images/random/'.$random.'.jpg';
		}
  return $first_img;
}

在主题中新建/images/random/目录,找一些自己喜欢的图片上传进去。将他们重命名为1,2,3,4,5.jpg。

调用代码:

<?php echo catch_first_image(); ?>

经测试发现,该代码仅返回随机缩略图地址。

插件

To Top - 返回顶部按钮wordpress插件

2020-4-14 17:24:13

国内主题

DukeYin - 多功能主题

2019-11-28 1:54:35

⚠️
Npcink上的部份代码及教程来源于互联网,仅供网友学习交流,若您喜欢本文可附上原文链接随意转载。
无意侵害您的权益,请发送邮件至 1355471563#qq.com 或点击右侧 私信:Muze 反馈,我们将尽快处理。
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索