Gimhoy's Blog

WordPress添加文章浏览历史记录功能

本文最后更新于2014年1月22日,已超过三年没有更新,如果文章内容失效,请反馈给我们,谢谢!

今天在逛博客的时候,发现有博主在侧边栏上加了个“浏览历史”的栏目,提醒访客曾经访问过那些文章。这样,当访客通过搜索等方式来到博客的时候,可能就会发现,其实之前也曾来过这个博客,对提高用户体验是个不错的方法。

MG12在《文章历史浏览记录》一文中,介绍了实现原理和实现步骤。这里再详细说下在WordPress博客中如何实现这个功能。
 

通过代码实现

1.将下面的代码保存为view-history.js 或者直接点击这里下载:view-history.js 放在主题文件夹的js文件夹中。

/**
* @author: mg12 [https://www.neoease.com/]
* @update: 2013/01/09
*
* IE6/7 need a third-party JSON library to polyfill this feature. [https://github.com/douglascrockford/JSON-js/blob/master/json2.js]
*/

ViewHistory = function() {

this.config = {
limit: 10,
storageKey: 'viewHistory',
primaryKey: 'url'
};

this.cache = {
localStorage: null,
userData: null,
attr: null
};
};

ViewHistory.prototype = {

init: function(config) {
this.config = config || this.config;
var _self = this;

// define localStorage
if (!window.localStorage && (this.cache.userData = document.body) && this.cache.userData.addBehavior && this.cache.userData.addBehavior('#default#userdata')) {
this.cache.userData.load((this.cache.attr = 'localStorage'));

this.cache.localStorage = {
'getItem': function(key) {
return _self.cache.userData.getAttribute(key);
},
'setItem': function(key, value) {
_self.cache.userData.setAttribute(key, value);
_self.cache.userData.save(_self.cache.attr);
}
};

} else {
this.cache.localStorage = window.localStorage;
}
},

addHistory: function(item) {
var items = this.getHistories();
for(var i=0, len=items.length; i<len; i++) {
if(item[this.config.primaryKey] && items[i][this.config.primaryKey] && item[this.config.primaryKey] === items[i][this.config.primaryKey]) {
items.splice(i, 1);
break;
}
}

items.push(item);

if(this.config.limit > 0 && items.length > this.config.limit) {
items.splice(0, 1);
}

var json = JSON.stringify(items);
this.cache.localStorage.setItem(this.config.storageKey, json);
},

getHistories: function() {
var history = this.cache.localStorage.getItem(this.config.storageKey);
if(history) {
return JSON.parse(history);
}
return [];
}
};

//引用脚本并初始化对象
/* <![CDATA[ */ 
if(typeof localStorage !== 'undefined' &amp;&amp; typeof JSON !== 'undefined') { 
var viewHistory = new ViewHistory(); 
viewHistory.init({ limit: 5, storageKey: 'viewHistory', primaryKey: 'url' }); 
} 
/* ]]> */

 

2.在主题文件夹下面的header.php中,插入下面这段代码加载js:

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/view-history.js"></script>

 

3.在主题文件夹下面的single.php中,插入下面这段代码:

<script>
//在文章页面保存浏览信息 
/* <![CDATA[ */
// 如果 ViewHistory 的实例存在,则可以将页面信息写入。
if(viewHistory) {
	var ptitle= document.getElementsByTagName('title')[0].innerHTML;
	var noname = ptitle.split(" | ");
    var page = {
        "title": noname[0],
        "url": location.href // 这是 primaryKey
        // "time": new Date()
        // "author": ...
        // 这里可以写入更多相关内容作为浏览记录中的信息
    };
    viewHistory.addHistory(page);
}
/* ]]> */
</script>

 

4.在需要显示“浏览历史”的地方添加代码:

<h3>您曾经看过:</h3>
<div id="view-history"></div>
//显示历史浏览记录 
/* <![CDATA[ */
var wrap = document.getElementById('view-history');
 
// 如果 ViewHistory 的实例存在,并且外层节点存在,则可显示历史浏览记录
if(viewHistory && wrap) {
    // 获取浏览记录
    var histories = viewHistory.getHistories();
 
    // 组装列表
    var list = document.createElement('ul');
    if(histories && histories.length > 0) {
        for(var i=histories.length-1; i>=0; i--) {
            var history = histories[i];
 
            var item = document.createElement('li');
            var link = document.createElement('a');
            link.href = history.url;
            link.innerHTML = history.title;
 
            item.appendChild(link);
            list.appendChild(item);
        }
 
        // 插入页面特定位置
        wrap.appendChild(list);
    }
}
/* ]]> */

 

或者直接在小工具中,添加一个“文本”,标题为“浏览历史”,内容填入以下代码:

<div id="view-history"></div>
//显示历史浏览记录 
/* <![CDATA[ */
var wrap = document.getElementById('view-history');
 
// 如果 ViewHistory 的实例存在,并且外层节点存在,则可显示历史浏览记录
if(viewHistory && wrap) {
    // 获取浏览记录
    var histories = viewHistory.getHistories();
 
    // 组装列表
    var list = document.createElement('ul');
    if(histories && histories.length > 0) {
        for(var i=histories.length-1; i>=0; i--) {
            var history = histories[i];
 
            var item = document.createElement('li');
            var link = document.createElement('a');
            link.href = history.url;
            link.innerHTML = history.title;
 
            item.appendChild(link);
            list.appendChild(item);
        }
 
        // 插入页面特定位置
        wrap.appendChild(list);
    }
}
/* ]]> */

 

使用插件实现

1.下载 wp-recently-viewed ,安装并启用;

2.进入WordPress后台 – 外观 – 小工具,找到 浏览历史,拖到右边你想要显示浏览历史的地方,填写标题并保存即可;

详见露兜博客

 

特别说明

有很多网友的文章标题后面带有博客名称,这样可能不太好看,如果你想去除标题中的博客名称,可以使用文件编辑器(记事本也行)打开:wp-recently-viewed/js/add-history.js,查找:

"title": document.getElementsByTagName('title')[0].innerHTML,

改成:

"title": noname[0],

然后再查找:

var page = {

改成:

var ptitle= document.getElementsByTagName('title')[0].innerHTML;
var noname = ptitle.split(" - "); 
var page = {

以上代码第2行的 – 就是你的文章标题跟博客名称的分隔符,请根据实际情况进行修改。



免费获得每月10G空间+10G免费流量
  • Comment (1)
  • Trackback (0)
  • 诸葛小觉 Google Chrome Windows 2013/10/22 13:24 @Ta

    挺不错的,就是感觉还要用IE6/7还要聚合第三方js挺麻烦的

    #25
  • 还没有Trackback
Leave a Reply

*

*