WordPress 添加文章浏览历史功能

本文目录[隐藏]1通过代码集成文章浏览历史功能2使用插件添加文章浏览历史功能2.1wp-recently-viewed2.1.1特别说明2.2类似插件 – Last Viewed Posts

让网站记住读者的浏览历史,让读者很方便地知道他最近阅读了你博客的哪些文章。这一举措,对于提高用户体验应该是不错的方法。那么,如何为你的WordPress站点添加这个功能?一起往下看吧!

2个多月前就在 neoease.com 看到 @MG12 的相关教程,也曾经在本地站点折腾过,还真的实现了。你可以按照 @MG12 文章历史浏览记录 这篇文章折腾。

通过代码集成文章浏览历史功能

折腾的时候是这样操作的:

1.将下面的代码另存为一个名为 view-history.js 的js文件(格式为 utf-8 无BOM)[代码来自于 @MG12]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
 * @author: mg12 [http://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' && typeof JSON !== 'undefined') {
    var viewHistory = new ViewHistory();
    viewHistory.init({
        limit: 5,
        storageKey: 'viewHistory',
        primaryKey: 'url'
    });
}
/* ]]> */
 
/* <![CDATA[ */
// 如果 ViewHistory 的实例存在,则可以将页面信息写入。
if(viewHistory) {
    var page = {
        "title": document.getElementsByTagName('title')[0].innerHTML,
        "url": location.href // 这是 primaryKey
        // "time": new Date()
        // "author": ...
        // 这里可以写入更多相关内容作为浏览记录中的信息
    };
    viewHistory.addHistory(page);
}
/* ]]> */
 
/* <![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);
    }
}
/* ]]> */

/**
* @author: mg12 [http://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’ && typeof JSON !== ‘undefined’) {
var viewHistory = new ViewHistory();
viewHistory.init({
limit: 5,
storageKey: ‘viewHistory’,
primaryKey: ‘url’
});
}
/* ]]> */ /* <![CDATA[ */
// 如果 ViewHistory 的实例存在,则可以将页面信息写入。
if(viewHistory) {
var page = {
"title": document.getElementsByTagName(‘title’)[0].innerHTML,
"url": location.href // 这是 primaryKey
// "time": new Date()
// "author": …
// 这里可以写入更多相关内容作为浏览记录中的信息
};
viewHistory.addHistory(page);
}
/* ]]> */ /* <![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);
}
}
/* ]]> */

2.将 view-history.js  放到你主题下的 js 文件夹中,然后在主题的 footer.php 中使用下面的代码调用:

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

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

3.如果你的主题支持小工具,你可以使用 [文本]小工具,添加标题为“浏览历史”,内容为“<div id="view-history"></div>”,然后保存,如下所示:

wpdaxue.com-201303521

就可以看到效果了:

wpdaxue.com-201303522

如果你的主题不支持小工具,就自己在需要显示的地方添加代码,代码中只要包含 id="view-history" 就能显示出浏览历史,比如:

1
2
<h3>浏览历史</h3>
<div id="view-history"></div>

<h3>浏览历史</h3>
<div id="view-history"></div>

使用插件添加文章浏览历史功能

wp-recently-viewed

@露兜 同学也根据这个方法制作了一个插件 wp-recently-viewed ,如果你不善于折腾代码,直接使用插件也是不错的选择。

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

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

3.上面是通过小工具来显示浏览历史,如果你不喜欢小工具或者你的主题没有小工具功能,而且你又懂得怎么修改主题代码,可以在你想要显示浏览历史的地方,插入以下HTML代码:

1
2
3
<div id="recently_viewed">
  <h3>您刚刚看过</h3>
</div>

<div id="recently_viewed">
<h3>您刚刚看过</h3>
</div>

这样,插件的JS代码就会自动在div内部追加浏览过的文章列表代码;当然你也可以使用其他的html框架,只要保证父级元素含有 id="recently_viewed" 就可以了,如你也可以这么写:

1
<li id="recently_viewed"></li>

<li id="recently_viewed"></li>

特别说明

有很多网友的文章标题后面带有博客名称,这样可能不太好看,如果你想去除标题中的博客名称,打开:wp-recently-viewed/js/add-history.js,查找:

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

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

改为

1
"title": noname[0],

"title": noname[0],

然后再查找:

1
var page = {

var page = {

改成:

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

var ptitle= document.getElementsByTagName(‘title’)[0].innerHTML;
var noname = ptitle.split(" – ");
var page = {

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

类似插件 – Last Viewed Posts

Last Viewed Posts 是老外写的一个插件,通过cookies保存读者的浏览历史。当然,每个读者只能看到自己的浏览历史。

参考资料:

http://www.neoease.com/recently-viewed-items/

http://www.ludou.org/wordpress-recently-viewed.html

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号