探索建站和运维乐趣

WordPress无需插件可实现随机缩略图调用的方法

在之前的文章中,我们有介绍到"WP Random Post Thumbnails"插件可以实现随机缩略图设置效果,但是我们有些时候制作主题的时候并不能强制网友使用某个插件,所以我们只能在主题中内置一些功能。比如我们可以使用无插件WordPress文章随机显示缩略图的方法。

//支持外链缩略图 Edit by laobuluo.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 = '';
		//从2张图中随机选择,可根据自己的图片数量设置
		$random = mt_rand(1, 10);
		echo get_bloginfo ( 'stylesheet_directory' );
		echo '/images/random/'.$random.'.JPG';
		}
  return $first_img;
}

我们将上面代码复制到当前主题的 Functions.php 文件中,检查兼容有没有问题,有问题需要排查。然后我们需要在主题"/images/random/"目录中。新建1-10.jpg 图片放到目录中。

然后我们在需要调用缩略图的文章列表合适位置调用。

<?php echo catch_first_image(); ?>

这样可以实现效果。

赞(1)
转载保留:老部落 » WordPress无需插件可实现随机缩略图调用的方法


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......