在我们开发制作wordpress主题中,大多都会做首页和列表页自动调用文章内第一张图片作为缩略图,如果文章内没有缩略图会显示默认缩略图,但是这样就会大量重复显示一张默认缩略图,很印象用户体验,下面这段代码正好解决wordpress文章随机显示缩略图,可以让文章缩略图随机显示,如果有缩略图就调用缩略图,没有缩略图会随机选取一张缩略图。
网上类似的教程也有很多,但是测试过几个代码都无效,甚至语法错误,以下是WP教程网亲测可用的一个版本:
//支持外链缩略图 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; }
使用方法
1、复制上面代码粘贴到主题functions.php中
2、在主题中新建/images/random/目录,找一些自己喜欢的图片上传进去。将他们重命名为1,2,3,4,5.jpg。
3、在想要展示缩略图的地方加入下面代码
<?php echo catch_first_image(); ?>