在WordPress中实现“您最近赏识过的文章”

时间:2014-01-26所属栏目: WordPress教程 来源: 热度:

在赏识许多大信息量网站时常常会看到“您最近赏识过的文章”这样的板块,固然看似蛋疼但在用户体验上来说确实拉近了亲和力,留下了用户的足迹,在某些环境下可以或许让用户找到之前的文章或思绪。

挪用最近赏识过的文章,道理是通过读取赏识器 cookie 文件,挪用表现最近被会见过的文章,必要留意的是,该成果不是统计全部赏识者最近查察过的文章,并没有写进数据库中,每个访客都有本身独占的赏识清单。

将这个成果运用到 WordPress主题 建造上仍需在 functions.php 文件上做文章,将下面代码添加到页面的最后:


<?php
$zg_cookie_expire = 360; // cookie逾期时刻,默认值是360天
$zg_number_of_posts = 10; // 表现篇数,默认值是10。
$zg_recognize_pages = true;

function zg_lwp_header() {
if (is_single()) {
zg_lw_setcookie();
} elseif (is_page()) {
global$zg_recognize_pages;
if ($zg_recognize_pages === true) {
zg_lw_setcookie();
}
}
}
function zg_lw_setcookie() {
global$wp_query;
$zg_post_ID = $wp_query->post->ID;
if (! isset($_COOKIE["WP-LastViewedPosts"])) {
$zg_cookiearray = array($zg_post_ID);
} else {
$zg_cookiearray = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"])));
if (! is_array($zg_cookiearray)) {
$zg_cookiearray = array($zg_post_ID);
}
}
if (in_array($zg_post_ID, $zg_cookiearray)) {
$zg_key = array_search($zg_post_ID, $zg_cookiearray);
array_splice($zg_cookiearray, $zg_key, 1);
}
array_unshift($zg_cookiearray, $zg_post_ID);
global$zg_number_of_posts;
while (count($zg_cookiearray) > $zg_number_of_posts) {
array_pop($zg_cookiearray);
}
$zg_blog_url_array = parse_url(get_bloginfo('url'));
$zg_blog_url = $zg_blog_url_array['host'];
$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'];
$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() {
echo '<ul class="viewed_posts">';
if (isset($_COOKIE["WP-LastViewedPosts"])) {
$zg_post_IDs = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"])));
foreach ($zg_post_IDsas$value) {
global$wpdb;
$zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");
foreach($zg_get_titleas$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";
}
}
} else {
}
echo '</ul>';
}
add_action('get_header','zg_lwp_header');
?>

标签:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)