Add article browsing history function to WordPress

This article was last updated on January 22, 2014. It has not been updated for more than three years. If the content of this article is invalid, please give us feedback. Thank you!

Today, when I visited the blog, I found that a blogger added a “browsing history” column in the sidebar to remind visitors that they had visited those articles. In this way, when visitors come to the blog through search and other means, they may find that they have been to the blog before, which is a good way to improve the user experience.

In the article “browsing history of articles”, mg12 introduces the implementation principle and steps. Here is how to implement this function in wordpress blog.
 

Through the code implementation

1. Save the following code as view- history.js Or click here to download: view- history.js Put it in the JS folder of the theme folder.

/**
* @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' &amp;&amp; typeof JSON !== 'undefined') { 
var viewHistory = new ViewHistory(); 
viewHistory.init({ limit: 5, storageKey: 'viewHistory', primaryKey: 'url' }); 
} 
/* ]]> */

 

2. Under the theme folder header.php To load JS, insert the following code:

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

 

3. Under the theme folder single.php Insert the following code:

<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. Add the code where you need to display “browsing history”:

<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);
    }
}
/* ]]> */

 

Or directly add a “text” in the widget with the title of “browsing history”, and fill in the following code for the content:

<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);
    }
}
/* ]]> */

 

Using plugins

1. Download WP recently viewed, install and enable it

2. Enter the background of WordPress – appearance – widget, find the browsing history, drag it to the right where you want to display the browsing history, fill in the title and save it

See Ludou blog for details

 

Special notes

Many netizens have a blog name behind the title of their articles, which may not be good-looking. If you want to remove the blog name from the title, you can use the file editor (Notepad is OK) to open it: WP recently viewed / JS / add- history.js , find:

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

Change to:

"title": noname[0],

Then look for:

var page = {

Change to:

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

The second line of the above code is the separator between the title of your article and the name of your blog. Please modify it according to the actual situation.

Related Article
Set the method for WordPress website to specify that the classified content will not be displayed on the home page

Sometimes, for the needs of specific content, we hope that the content of a certain category will not be displayed Read more

Remove the default link function of WordPress upload image

Our friends have found out when using WordPress program that if there is no manually set link for the uploaded Read more

WordPress excludes the specified articles / categories from being displayed by on-site search

WordPress is the most used CMS program at present. As long as we need some functions, we can basically search Read more

WordPress details optimization to automatically add ALT and title information to the article image

Friends who know a little bit about SEO optimization should understand that image ALT and image title optimization are very Read more

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image