如果你是第一次来到本站,又是第一次阅览文章,只要你刷新一下页面,就可以在右边栏见到效果了。这也许是真正意义上的足迹吧,看过文章就给记录,不管你是潜水也好,水车也好。实现原理是给客户端浏览器加个cookie,每访问一次记录一次,服务器表示无压力。。。
实现步骤一:把以下代码加入WordPress主题内的function.php中----
<?php
function save_posts_viewed($maxCount=10){
global $post;
$done=false;
//新列
$newList=array();
$postsViewed="";
if(isset($_COOKIE['postsViewed'])){
$postsViewed=$_COOKIE['postsViewed'];
}
if(isset($_COOKIE['postsViewed'])&&$postsViewed!=array()){
$repeat=null;
$repeated=false;
foreach ($postsViewed as $k=>$p){
if($p['ID']==$post->ID){
$repeat=$p;
$repeated=true;
}
else
$newList[]=$p;
}
if($repeated)
$newList[]=$repeat;
else
$newList[]=array(
'ID'=>$post->ID,
'post_title'=>$post->post_title,
'post_date'=>$post->post_date,
'viewed_date'=>time()
);
}else{
$newList[]=array(
'ID'=>$post->ID,
'post_title'=>$post->post_title,
'post_date'=>$post->post_date,
'viewed_date'=>time()
);
}
if(count($newList)>$maxCount){
$newList2=array();
$m=1;
foreach ($newList as $n){
if($m>count($newList)-$maxCount)
$newList2[]=$n;
$m++;
}
$newList=$newList2;
}
creatCookiesList($newList);
}
function creatCookiesList($newList){
//setcookie("postsViewed",'', COOKIEPATH, COOKIE_DOMAIN);
foreach ($newList as $k=>$n){
setcookie("postsViewed[$k][ID]",$n['ID'],time()+3600*24*365,COOKIEPATH, COOKIE_DOMAIN);
setcookie("postsViewed[$k][post_title]",$n['post_title'],time()+3600*24*365, COOKIEPATH, COOKIE_DOMAIN);
setcookie("postsViewed[$k][post_date]",$n['post_date'],time()+3600*24*365, COOKIEPATH, COOKIE_DOMAIN);
setcookie("postsViewed[$k][viewed_date]",$n['viewed_date'],time()+3600*24*365, COOKIEPATH, COOKIE_DOMAIN);
}
}
function get_posts_viewed(){
if(isset($_COOKIE['postsViewed'])){
$list=$_COOKIE['postsViewed'];
$num=0;
for ($i=count($list)-1;$i>=0;$i--){
$num++;
?>
<li style="height:16px;"><span style="margin-right:5px;"><?php echo $num;?>?</span><a href="<?php echo get_permalink($list[$i]['ID'])?>" title="您在 <?php echo date('Y-m-d h:i',$list[$i]['viewed_date'])?>观看了这篇文章"><?php echo $str=$list[$i]['post_title']?></a></li>
<?php }
}else {?>
<li>你没有浏览过任何文章或者你没有开启cookies。</li>
<?php }
}
实现步骤二:
1、先在single.php主循环里面加上(比如get_header();这个函数后面):
<?php save_posts_viewed(10);?>数字10是记录数量,你可以自己更改。
2、然后在页面任意适合的地方(我放在sidebar.php)里面输出:
<?php get_posts_viewed();?>
有关css怎么写,每个人的主题不一样,就不好提供了。
几点说明:
1、如果你不要文章标题前的序列号,可以删除代码:
<span style="margin-right:5px;"><?php echo $num;?>?</span>
2、如果你是国外主机(服务器时间与北京时间不同),建议删除代码:
title="您在 <?php echo date('Y-m-d h:i',$list[$i]['viewed_date'])?>观看了这篇文章"
恩,很好,跟着楼主学习了。www.dq30.net