一开始搭建APTX部落这个博客时,博客的图片都用的Vicer大佬的,最近有时间了,便把图片大部分换成自己找的了(感谢P站各位画师),每个文章设置特色图像太麻烦了,怎么才能让他随机显示呢,就像萌咖一样。
教程
1、编辑主题文件,在主题的functions.php中加入以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //支持外链缩略图 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都去掉即可 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; } |
2、在主题中新建/images/random/目录,找一些自己拍的图片放进去。将他们重命名为1..2…3..4..5.jpg网上有一件重命名脚本/
3、打开主题目录下content.php,将原主题的特色图像代码换成下面的
1 2 3 4 | <!—裁切高大于宽的图片—> <div style=“overflow:hidden;width:100%;max-height:100px;”> <img src=‘<?php echo catch_first_image(); ?>‘ /> </div> |
如下图(KRATOS)