WordPress随机显示缩略图的实现方法

2022年10月11日 / 龙哥随笔 / 0 条 / 502次

在我们开发制作WordPress主题中,大多都会做首页和列表页自动调用文章内第一张图片作为缩略图,如果文章内没有缩略图会显示默认缩略图,但是这样就会大量重复显示一张默认缩略图,很印象用户体验,下面这段代码正好解决WordPress文章随机显示缩略图,可以让文章缩略图随机显示,如果有缩略图就调用缩略图,没有缩略图会随机选取一张缩略图。

如果不希望缩略图随机显示,也可以换成自动获取文章内第一张图片做为缩略图。

网上类似的教程也有很多,但是测试过几个代码都无效,甚至语法错误,以下是亲测可用的一个版本:

方法如下:

1、复制下面代码粘贴到主题functions.php中。

  1. //支持外链缩略图 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; }

注意:$random = mt_rand(1, 2);为图片编号数量。比如图片有1.jpg,2.jpg,....30.jpg,那么修改成:$random = mt_rand(1, 30);

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

3、在想要展示缩略图的地方(替换链接图片地址)加入下面代码。

  1. <?php echo catch_first_image(); ?>


提交评论