最近在站點主題更新的時候,由於糢板和外掛過多總會經常性的忘記設定熱點圖片,一單忘記設定熱點圖片就會整個頁面特別的醜,想了很多辦法最後才算是搞定了。設定完畢後就算忘記設定了特色圖片系統也會隨機顯示一張圖片。
編輯主題文件,在主題的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 = ''; //從2張圖中隨機選擇,可根據自己的圖片數量設定 $random = mt_rand(1, 2); echo get_bloginfo ( 'stylesheet_directory' ); echo '/images/random/'.$random.'.jpg'; } return $first_img; }
在主題中新建/images/random/目錄,找一些自己拍的圖片放進去。將他們重命名為1..2…3..4..5.jpg
打開主題目錄下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().'" target="_blank" rel="external nofollow" ><img src="'.$imgg_url.'" /></a>'; }
content.php:
<?php echo catch_rand_image(); ?>
原创文章,作者:然星,如若转载,请注明出处:https://gov.com.sb/wordpress-4.html