[WordPress Tips] 隨機改變頁首背景底圖!
文章歸類:Blog / Wordpress / 網頁設計 / 資訊科技。
文章標簽: PHP / Web Design / Web Developing / Wordpress。
之前個人相當鍾愛極簡風格的網頁樣板,然而,最近攝影作品越來越多,因此想換換風格,希望可以在我的部落格上直接展現我的一些攝影作品。而我想:將攝影作品直接設為頁首的底圖應該會是一個不錯的選擇!然而,一般的頁首底圖通常是不會變動的,如果一次只能顯示一個底圖,之後都必須手動更換的話,這種做法有些麻煩,而且無法滿足我想展示攝影作品的慾望,因此,開始上網搜尋相關的資訊,想找找是否有可以隨機改變頁首背景底圖的方法,也就是說,每次使用者重新載入 (reload) 頁面時,頁首的背景底圖便會更換一次,如此便可以讓網頁風格看起來比較活潑多變一些!
在請示過 Google 大神後發現,有許多種方法可以實現這個功能,甚至還有現成的 Plugin 可以使用,然而,小弟最後選擇的是一種不需要安裝 Plugin 的方法,這個做法相當簡單而且易懂,以下便來簡單說明一下安裝步驟:
步驟一:新增一個用來操控圖片 PHP 腳本(Script)。
例如:我新增了一個 random.php 檔案,然後將以下的程式碼貼上。
<?php
/*
By Matt Mullenweg
> http://photomatt.net
Inspired by Dan Benjamin
> http://hiveware.com/imagerotator.php
Latest version always at
> http://photomatt.net/scripts/randomimage
*/
// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = ' ';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
// Initialize some variables
$files = array(); $i = -1;
if ('' == $folder)
$folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
// for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) {
// faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle);
// We're not using it anymore
mt_srand((double)microtime()*1000000);
// seed for PHP < 4.2
$rand = mt_rand(0, $i);
// $i was incremented as we went along
header('Location: '.$folder.$files[$rand]);
// Voila!
?>
步驟二:設定變數。
以上的程式碼有兩個地方需要做些修正:
- 設定 $folder 變數,以指定圖片的目錄路徑。
- 設定 $exts 變數,以指定圖片的副檔名。
步驟三:上傳圖片。
上傳你要用來作為頁首底圖的圖片,到 $folder 變數所指定的目錄中。
步驟四:安裝這個功能。
在你要顯示頁首底圖的地方呼叫步驟一的 Script。安裝的方法有兩種 (擇一即可):
- 使用 CSS。也就是修改 style.css,將 header 的 background 屬性指向步驟一的 Script。做法如下所示:
- 使用 html 的 img 標簽。將 src 的屬性指向步驟一的 Script。做法如下所示:
#header {
background: #fff url(步驟一的 Script 的檔案路徑) no-repeat 0px 0px;
}
<img src="步驟一的 Script 的檔案路徑" alt="A Random Image" />
以上,大功告成!
最後,附上原作者的教學網頁:Random Image Script — Matt Mullenweg。


