腾讯云服务器优惠活动华纳云香港服务器

如何让HotNews主题不同分类显示不同的随机缩略图

WordPress主题推荐

HotNews 主题集成的随机缩略图本来是为懒人准备的,可能有童鞋感觉,不同的分类内容都显示相同的随机缩略图,有些不搭调,如果博客日志较多,文章中又无图片,重新编辑添加图片工作量又太大,来个折中的办法,改动一下随机缩略图调用函数,让不同的分类显示不同的随机缩略图。

首先,在 HotNews 主题 images 目录新建名称为:random1、random2、random3………文件夹,并在其中放置不同的随机缩略图片,图片名称必须是连续的

其次,打开主题 functions.php 模版,找到:

  1. //支持外链缩略图
  2. if ( function_exists(‘add_theme_support’) )
  3.  add_theme_support(‘post-thumbnails’);
  4.  /*Catch first image (post-thumbnail fallback) */
  5.  function catch_first_image() {
  6.   global $post$posts;
  7.   $first_img = ;
  8.   ob_start();
  9.   ob_end_clean();
  10.   $output = preg_match_all(‘/<img.+src=[\’“]([^\'”]+)[\'”].*>/i’, $post->post_content, $matches);
  11.   $first_img = $matches [1] [0];
  12.   if(emptyempty($first_img)){ //Defines a default image
  13.         $random = mt_rand(1, 20);
  14.         echo get_bloginfo ( ‘stylesheet_directory’ );
  15.         echo ‘/images/random/’.$random.’.jpg’;
  16.   }
  17.   return $first_img;
  18.  }

替换为:

  1. //支持外链缩略图
  2. if ( function_exists(‘add_theme_support’) )
  3.  add_theme_support(‘post-thumbnails’);
  4.  /*Catch first image (post-thumbnail fallback) */
  5.  function catch_first_image() {
  6.   global $post$posts;
  7.   $first_img = ;
  8.   ob_start();
  9.   ob_end_clean();
  10.   $output = preg_match_all(‘/<img.+src=[\’“]([^\'”]+)[\'”].*>/i’, $post->post_content, $matches);
  11.   $first_img = $matches [1] [0];
  12. if(emptyempty($first_img)){ //Defines a default image
  13.     $random = mt_rand(1, 20);
  14.     echo get_bloginfo ( ‘stylesheet_directory’ );
  15. if ( is_category( ‘472’ ) ) {
  16.     echo ‘/images/random1/’.$random.’.jpg’;
  17.  } elseif ( is_category( ‘473’ ) ) {
  18.     echo ‘/images/random2/’.$random.’.jpg’;
  19.  } elseif ( is_category( ‘474’ ) ) {
  20.     echo ‘/images/random3/’.$random.’.jpg’;
  21.  }
  22.  }
  23.   return $first_img;
  24.  }

其中:

数字 20 是随机缩略图数量,根据实际自行修改。

修改上面代码类似“ is_category( ‘472’ )”中数字为相应的分类 ID 号

random3 是图片文件夹的名称

如果分类较多,可以多复制几个:

  1. elseif ( is_category( ‘474’ ) ) {
  2.     echo ‘/images/random3/’.$random.’.jpg’;
  3.  }

同样要修改其中的分类 ID 及图片文件夹名称。

注:此方法只支持分类页面,首页无效

赞 (0) 打赏
版权声明:本文为转载文章,来源于 知更鸟 ,版权归原作者所有!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu