欢迎光临
我们一直在努力

如何设置WordPress缩略图显示随机图片

如何设置WordPress缩略图显示随机图片,原本的是默认获取文章的第一张图片。那么如何把图片换成自己找的呢?每个文章设置特色图像也非常的麻烦,如何才能让他随机显示呢。方法如下:

1、编辑主题文件,在主题的functions.php中加入以下代码

//支持外链缩略图
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 = '';
    //从6张图中随机选择,可根据自己的图片数量设置
    $random = mt_rand(1, 2,3,4,5,6);//这里是调取文件夹中的文件名,如果图片不够的话可以删除即可。
    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,将以下代码替换原有的特色图像代码

<!--裁切高大于宽的图片-->
<div  style="overflow:hidden;width:100%;max-height:100px;">
<img src='<?php echo catch_first_image(); ?>' />
</div>

如果加完没有连接的话,可以使用这个:

function catch_rand_image() {
  global $post, $posts;$imgg_url;
  ob_start();
  ob_end_clean();
    $random = mt_rand(1, 63);
    $imgg_url = 'https://xxx/images/random/'.$random.'.jpg';
    echo '<a href="'.get_permalink().'"><img src="'.$imgg_url.'" /></a>';
}

 

赞(0) 打赏
未经允许不得转载:新起点博客 » 如何设置WordPress缩略图显示随机图片


关注公众号『新起点软件管家』

获取最新网络资源及破解软件!
带你玩转各样软件...

评论 抢沙发

评论前必须登录!

 

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

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏