2010-02-16 33 views
0

我認爲(希望)我的問題比我說的更簡單,但這也是我在Google上空虛的原因。這是與此類似,但我需要處理一些HTML用它,我有點不清楚:Random image display如何在wordpress側邊欄中旋轉兩張圖片?

在我的WordPress的側邊欄安裝我在這個順序兩個圖像:

<a href="http://www.link1.tld"><img src="files/image1.jpg" border="0" /></a> 
<a href="http://www.link2.tld"><img src="files/image2.jpg" border="0" /></a> 

什麼是最簡單的在頁面刷新時完成旋轉此順序的方式(以便訂單將成爲image2/image1)?並在下次刷新時,返回到image1/image2?

+0

你希望它永遠旋轉或可隨機? – nortron

+0

理想情況下,我希望它旋轉 - 我已更新標題以反映,謝謝。 – scraft3613

回答

1

要做到這一點,你需要存儲一個視圖計數器與用戶一個cookie,然後根據該計數器顯示:

session_start(); 
if(!isset($_SESSION['views'])) { 
    $_SESSION['views'] = 0; 
} 
else { 
    $_SESSION['views']++; 
} 

,然後顯示:

<?php if($_SESSION['views'] % 2 == 0): ?> 
<a href="http://www.link1.tld"><img src="files/image1.jpg" border="0" /></a> 
<? endif; ?> 
<a href="http://www.link2.tld"><img src="files/image2.jpg" border="0" /></a> 
<?php if($_SESSION['views'] % 2 == 1): ?> 
<a href="http://www.link1.tld"><img src="files/image1.jpg" border="0" /></a> 
<? endif; ?> 

如果查看計數器甚至會首先打印image1。如果它很奇怪,它會打印第二個。

縮放這兩個以上的圖像可以做這樣的:

// map of images to URLs 
$images = array(
    'image1.jpg' => 'http://www.link1.tld', 
    'image2.jpg' => 'http://www.link2.tld', 
    'image3.jpg' => 'http://www.link3.tld', 
    'image4.jpg' => 'http://www.link4.tld', 
); 

// reorder the list of images based on the current view count 
$ordered = array_merge(array_slice($images, $_SESSION['views'] % count($images)), array_slice($images, 0, $_SESSION['views'] % count($images))); 

,然後顯示只有通過有序列表循環:

<?php foreach($ordered as $image => $url): ?> 
<a href="<?php echo $url; ?>"><img src="files/<?php echo $image; ?>" border="0" /></a> 
<?php endforeach; ?> 
+0

從技術上講,您將計數值存儲在會話中,並且用戶接收到帶有會話ID的cookie,以便PHP可以將會話分配給用戶,但會話數據不會存儲在客戶端(除了某些實現不要使用像codeigniter這樣的本地PHP會話) – Residuum

+0

獲取「Warning:session_start()[function.session-start]:無法發送會話cookie - 已經發送的頭文件(輸出開始於/ home/wp-content/plugins/audio-player /audio-player.php:663)在/home/wp-content/themes/softpattern/sidebar.php在線86「 如果我禁用插件,我得到了不同的插件相同的錯誤。應該在哪裏放置php的session_start()部分? – scraft3613

+1

@ scraft3613 session_start()必須在任何輸出發送到瀏覽器之前調用,並且應該移出側邊欄文件,可能是wp-config.php。查看詳情:http://www.frank-verhoeven.com/using-session-in-wordpress/ – nortron