方法一 利用php来实现
原理是通过读取浏览器cookie文件,调用显示最近(360天 可选参数)被访问过的(10篇,可选参数)文章 ,需要注意的是,该功能不是统计所有浏览者最近查看过的文章,并没有写进数据库中,每个访客都有自己独有的浏览清单。
直接放到fuctions中。
<code>
/* Here are some parameters you may want to change: */
$zg_cookie_expire = 360; // 可选参数 默认360天
$zg_number_of_posts = 10; // 可选参数 默认10篇文章
$zg_recognize_pages = true;
/* Do not edit after this line! */
function zg_lwp_header() { // Main function is called every time a page/post is being generated
if (is_single()) {
zg_lw_setcookie();
} else if (is_page()) {
global $zg_recognize_pages;
if ($zg_recognize_pages === true) {
zg_lw_setcookie();
}
}
}
function zg_lw_setcookie() { // Do the stuff and set cookie
global $wp_query;
$zg_post_ID = $wp_query->post->ID; // Read post-ID
if (! isset($_COOKIE["WP-LastViewedPosts"])) {
$zg_cookiearray = array($zg_post_ID); // If there's no cookie set, set up a new array
} else {
$zg_cookiearray = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it
if (! is_array($zg_cookiearray)) {
$zg_cookiearray = array($zg_post_ID); // If array is fucked up...just build a new one.
}
}
if (in_array($zg_post_ID, $zg_cookiearray)) { // If the item is already included in the array then remove it
$zg_key = array_search($zg_post_ID, $zg_cookiearray);
array_splice($zg_cookiearray, $zg_key, 1);
}
array_unshift($zg_cookiearray, $zg_post_ID); // Add new entry as first item in array
global $zg_number_of_posts;
while (count($zg_cookiearray) > $zg_number_of_posts) { // Limit array to xx (zg_number_of_posts) entries. Otherwise cut off last entry until the right count has been reached
array_pop($zg_cookiearray);
}
$zg_blog_url_array = parse_url(get_bloginfo('url')); // Get URL of blog
$zg_blog_url = $zg_blog_url_array['host']; // Get domain
$zg_blog_url = str_replace('www.', '', $zg_blog_url);
$zg_blog_url_dot = '.';
$zg_blog_url_dot .= $zg_blog_url;
$zg_path_url = $zg_blog_url_array['path']; // Get path
$zg_path_url_slash = '/';
$zg_path_url .= $zg_path_url_slash;
global $zg_cookie_expire;
setcookie("WP-LastViewedPosts", serialize($zg_cookiearray), (time()+($zg_cookie_expire*86400)), $zg_path_url, $zg_blog_url_dot, 0);
}
function zg_recently_viewed() { // Output
echo '<ul class="viewed_posts">';
if (isset($_COOKIE["WP-LastViewedPosts"])) {
//echo "Cookie was set.<br/>"; // For bugfixing - uncomment to see if cookie was set
//echo $_COOKIE["WP-LastViewedPosts"]; // For bugfixing (cookie content)
$zg_post_IDs = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it
foreach ($zg_post_IDs as $value) { // Do output as long there are posts
global $wpdb;
$zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");
foreach($zg_get_title as $zg_title_out) {
echo "<li><a href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\">". $zg_title_out->post_title . "</a></li>\n"; // Output link and title
}
}
} else {
//echo "No cookie found."; // For bugfixing - uncomment to see if cookie was not set
}
echo '</ul>';
}
function zg_lwp_widget($args) { // Widget output
extract($args);
$options = get_option('zg_lwp_widget');
$title = htmlspecialchars(stripcslashes($options['title']), ENT_QUOTES);
$title = emptyempty($options['title']) ? 'Last viewed posts' : $options['title'];
if (isset($_COOKIE["WP-LastViewedPosts"])) {
echo $before_widget . $before_title . $title . $after_title;
zg_recently_viewed();
echo $after_widget;
}
}
function zg_lwp_widget_control() { // Widget control
$options = $newoptions = get_option('zg_lwp_widget');
if ( $_POST['lwp-submit'] ) {
$newoptions['title'] = strip_tags(stripslashes($_POST['lwp-title']));
}
if ( $options != $newoptions ) {
$options = $newoptions;
update_option('zg_lwp_widget', $options);
}
$title = attribute_escape( $options['title'] );
?>
<p><label for="lwp-title">
<?php _e('Title:') ?> <input type="text" style="width:250px" id="lwp-title" name="lwp-title" value="<?php echo $title ?>" /></label>
</p>
<input type="hidden" name="lwp-submit" id="lwp-submit" value="1" />
<?php
}
function zg_lwp_init() { // Widget init
if ( !function_exists('register_sidebar_widget') )
return;
register_sidebar_widget('Last Viewed Posts','zg_lwp_widget');
register_widget_control('Last Viewed Posts','zg_lwp_widget_control', 250, 100);
}
add_action('get_header','zg_lwp_header');
add_action('widgets_init', 'zg_lwp_init');
</code>
/* Here are some parameters you may want to change: */
$zg_cookie_expire = 360; // 可选参数 默认360天
$zg_number_of_posts = 10; // 可选参数 默认10篇文章
$zg_recognize_pages = true;
/* Do not edit after this line! */
function zg_lwp_header() { // Main function is called every time a page/post is being generated
if (is_single()) {
zg_lw_setcookie();
} else if (is_page()) {
global $zg_recognize_pages;
if ($zg_recognize_pages === true) {
zg_lw_setcookie();
}
}
}
function zg_lw_setcookie() { // Do the stuff and set cookie
global $wp_query;
$zg_post_ID = $wp_query->post->ID; // Read post-ID
if (! isset($_COOKIE["WP-LastViewedPosts"])) {
$zg_cookiearray = array($zg_post_ID); // If there's no cookie set, set up a new array
} else {
$zg_cookiearray = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it
if (! is_array($zg_cookiearray)) {
$zg_cookiearray = array($zg_post_ID); // If array is fucked up...just build a new one.
}
}
if (in_array($zg_post_ID, $zg_cookiearray)) { // If the item is already included in the array then remove it
$zg_key = array_search($zg_post_ID, $zg_cookiearray);
array_splice($zg_cookiearray, $zg_key, 1);
}
array_unshift($zg_cookiearray, $zg_post_ID); // Add new entry as first item in array
global $zg_number_of_posts;
while (count($zg_cookiearray) > $zg_number_of_posts) { // Limit array to xx (zg_number_of_posts) entries. Otherwise cut off last entry until the right count has been reached
array_pop($zg_cookiearray);
}
$zg_blog_url_array = parse_url(get_bloginfo('url')); // Get URL of blog
$zg_blog_url = $zg_blog_url_array['host']; // Get domain
$zg_blog_url = str_replace('www.', '', $zg_blog_url);
$zg_blog_url_dot = '.';
$zg_blog_url_dot .= $zg_blog_url;
$zg_path_url = $zg_blog_url_array['path']; // Get path
$zg_path_url_slash = '/';
$zg_path_url .= $zg_path_url_slash;
global $zg_cookie_expire;
setcookie("WP-LastViewedPosts", serialize($zg_cookiearray), (time()+($zg_cookie_expire*86400)), $zg_path_url, $zg_blog_url_dot, 0);
}
function zg_recently_viewed() { // Output
echo '<ul class="viewed_posts">';
if (isset($_COOKIE["WP-LastViewedPosts"])) {
//echo "Cookie was set.<br/>"; // For bugfixing - uncomment to see if cookie was set
//echo $_COOKIE["WP-LastViewedPosts"]; // For bugfixing (cookie content)
$zg_post_IDs = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it
foreach ($zg_post_IDs as $value) { // Do output as long there are posts
global $wpdb;
$zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");
foreach($zg_get_title as $zg_title_out) {
echo "<li><a href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\">". $zg_title_out->post_title . "</a></li>\n"; // Output link and title
}
}
} else {
//echo "No cookie found."; // For bugfixing - uncomment to see if cookie was not set
}
echo '</ul>';
}
function zg_lwp_widget($args) { // Widget output
extract($args);
$options = get_option('zg_lwp_widget');
$title = htmlspecialchars(stripcslashes($options['title']), ENT_QUOTES);
$title = emptyempty($options['title']) ? 'Last viewed posts' : $options['title'];
if (isset($_COOKIE["WP-LastViewedPosts"])) {
echo $before_widget . $before_title . $title . $after_title;
zg_recently_viewed();
echo $after_widget;
}
}
function zg_lwp_widget_control() { // Widget control
$options = $newoptions = get_option('zg_lwp_widget');
if ( $_POST['lwp-submit'] ) {
$newoptions['title'] = strip_tags(stripslashes($_POST['lwp-title']));
}
if ( $options != $newoptions ) {
$options = $newoptions;
update_option('zg_lwp_widget', $options);
}
$title = attribute_escape( $options['title'] );
?>
<p><label for="lwp-title">
<?php _e('Title:') ?> <input type="text" style="width:250px" id="lwp-title" name="lwp-title" value="<?php echo $title ?>" /></label>
</p>
<input type="hidden" name="lwp-submit" id="lwp-submit" value="1" />
<?php
}
function zg_lwp_init() { // Widget init
if ( !function_exists('register_sidebar_widget') )
return;
register_sidebar_widget('Last Viewed Posts','zg_lwp_widget');
register_widget_control('Last Viewed Posts','zg_lwp_widget_control', 250, 100);
}
add_action('get_header','zg_lwp_header');
add_action('widgets_init', 'zg_lwp_init');
</code>
不过自己要从新写CSS样式。
调用方式
<code><?php zg_recently_viewed(); ?></code>
方法二 利用jQuery来实现
基本流程:
1、获取文章详情页面文章的标题和页面地址;
2、获取浏览历史cookie信息,判断如果浏览历史的cookie中已经存在当前文章的浏览记录,则不进行任何操作;
3、如果浏览历史的cookie中不存在当前文章的浏览记录,则将当前文章的cookie信息(文章标题和页面地址)写入浏览历史的cookie信息中。写入的cookie信息,采用JSON数据格式,便于读取。
4、获取浏览历史cookie信息,遍历JSON数据,分析并输出浏览历史记录。
详细的方法:
1、首先加载jquery.cookie.js插件。
<code>/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (arguments.length > 1 && String(value) !== "[object Object]") {
options = jQuery.extend({}, options);
if (value === null || value === undefined) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};</code>
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {
// key and at least value given, set cookie...
if (arguments.length > 1 && String(value) !== "[object Object]") {
options = jQuery.extend({}, options);
if (value === null || value === undefined) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = String(value);
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};</code>
2、jQuery代码
<code>//文章浏览历史记录
var art_title = $(".history h2").text(); //文章标题,根据自己的来修改,追加一个history属性;
var art_url =document.location.href; //页面地址
var canAdd = true; //初始可以插入cookie信息
var hisArt = $.cookie("hisArt");
var len = 0;
if(hisArt){
hisArt = eval("("+hisArt+")");
len = hisArt.length;
}
$(hisArt).each(function(){
if(this.title == art_title){
canAdd = false;
return false;
}
});
if(canAdd==true){
var json = "[";
var start = 0;
if(len>5){start = 1;} //其中5为显示文章的数量
for(var i=start;i<len;i++){
json = json + "{\"title\":\""+hisArt[i].title+"\",\"url\":\""+hisArt[i].url+"\"},";
}
json = json + "{\"title\":\""+art_title+"\",\"url\":\""+art_url+"\"}]";
$.cookie("hisArt",json,{expires:1});
}
$(function(){
var json = eval("("+$.cookie("hisArt")+")");
var list = "";
for(var i=1; i<json.length;i++){
list = list + "<li><a href='"+json[i].url+"' target='_blank'>"+json[i].title+"</a></li>";
}
$("#sidebarlist").html(list); //需要显示地方DIV的id,需要修改
});</code>
var art_title = $(".history h2").text(); //文章标题,根据自己的来修改,追加一个history属性;
var art_url =document.location.href; //页面地址
var canAdd = true; //初始可以插入cookie信息
var hisArt = $.cookie("hisArt");
var len = 0;
if(hisArt){
hisArt = eval("("+hisArt+")");
len = hisArt.length;
}
$(hisArt).each(function(){
if(this.title == art_title){
canAdd = false;
return false;
}
});
if(canAdd==true){
var json = "[";
var start = 0;
if(len>5){start = 1;} //其中5为显示文章的数量
for(var i=start;i<len;i++){
json = json + "{\"title\":\""+hisArt[i].title+"\",\"url\":\""+hisArt[i].url+"\"},";
}
json = json + "{\"title\":\""+art_title+"\",\"url\":\""+art_url+"\"}]";
$.cookie("hisArt",json,{expires:1});
}
$(function(){
var json = eval("("+$.cookie("hisArt")+")");
var list = "";
for(var i=1; i<json.length;i++){
list = list + "<li><a href='"+json[i].url+"' target='_blank'>"+json[i].title+"</a></li>";
}
$("#sidebarlist").html(list); //需要显示地方DIV的id,需要修改
});</code>
3、在页面显示:
<code><div class="sidebarhistory">
<h4>文章浏览记录</h4>
<ul id="sidebarlist">
</ul>
</div></code>
<h4>文章浏览记录</h4>
<ul id="sidebarlist">
</ul>
</div></code>
4、CSS美化:
<code>.sidebarhistory h4{font-size: 14px;color: #585858;margin: 30px 0px 10px 0px;background: url(images/sidebar-list.png) no-repeat 3px 5px;padding-left: 28px;font-weight: bold;}
.sidebarhistory ul li{width: 230px;height: 32px;display: block;overflow: hidden;float:left;border-bottom:1px dashed #D0D0D0;line-height:32px;background:url(images/list.png) no-repeat 0 12px;text-indent:1.1em;list-style: none;}</code>
.sidebarhistory ul li{width: 230px;height: 32px;display: block;overflow: hidden;float:left;border-bottom:1px dashed #D0D0D0;line-height:32px;background:url(images/list.png) no-repeat 0 12px;text-indent:1.1em;list-style: none;}</code>
5、需要在文章页面的标题处追加一个class属性,比如我现在是:
<code><div class="post-title history"></code>
就是利用history这个属性来区分需要调用部分,其他部分不调用。如果你需要调用其他部分,那也可以添加相应的属性。
##方法二来自 www.cgrabbit.info/blog/recently-viewed-items-cookie-json.html