如何在wordpress侧边栏中旋转两张图片?

问题描述:

我认为(希望)我的问题比我说的更简单,但这也是我在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

要做到这一点,你需要存储一个视图计数器与用户一个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