首页 > WordPress学习 > WordPress纯代码实现文章随机缩略图调用的方法(无需插件)

WordPress纯代码实现文章随机缩略图调用的方法(无需插件)

时间:2021年12月16日 分类:WordPress学习 浏览量:356

在主题的Functions.php文件中,添加如下代码:

//随机缩略图 Edit by https://news.yynnw.com
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 = '';
		//从10张图中随机选择,可根据自己的图片数量设置
		$peitu= mt_rand(1, 10);
		echo get_bloginfo ( 'stylesheet_directory' );
		//以下路径可根据不同的主题设置或新建
		echo '/img/peitu/'.$peitu.'.jpg';
		}
  return $first_img;
}

接着在主题的img目录下,新建一个peitu目录,然后将图片放入,命名为1到10的jpg图片即可。

然后在我们需要调用的地方,放置如下调用代码:

<?php echo catch_first_image() ?>

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权

文章名称:WordPress纯代码实现文章随机缩略图调用的方法(无需插件)

文章链接:https://news.yynnw.com/5.html

该作品系作者结合个人学习经验及互联网相关知识整合。如若侵权请通过投诉通道提交信息,我们将按照规定及时处理。

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签:

最新文章

猜你喜欢