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

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

时间:2022年6月15日 分类:WordPress 浏览量:342

在主题的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() ?>

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

微信扫一扫打赏

标签: