让网站记住读者的浏览历史,让读者很方便地知道他最近阅读了你博客的哪些文章。这一举措,对于提高用户体验应该是不错的方法。那么,如何为你的WordPress站点添加这个功能?一起往下看吧!
把下面的代码添加到主题目录下的functions.php(请备份再操作)文件里即可
1. /* 可选参数: */
2. $zg_cookie_expire =360;// cookie过期时间,默认值是360天
3. $zg_number_of_posts =10;// 显示篇数,默认值是10。
4. $zg_recognize_pages =true;
5.
6. /* 此行后不要编辑 */
7. function zg_lwp_header(){
8. if(is_single()){
9. zg_lw_setcookie();
10. }elseif(is_page()){
11. global $zg_recognize_pages;
12. if($zg_recognize_pages ===true){
13. zg_lw_setcookie();
14. }
15. }
16. }
17.
18. function zg_lw_setcookie(){
19. global $wp_query;
20. $zg_post_ID = $wp_query->post->ID;
21. if(! isset($_COOKIE["WP-LastViewedPosts-coding3min"])){
22. $zg_cookiearray = array($zg_post_ID);
23. }else{
24. $zg_cookiearray = unserialize(stripslashes($_COOKIE["WP-LastViewedPosts-coding3min"]));
25. if(! is_array($zg_cookiearray)){
26. $zg_cookiearray = array($zg_post_ID);
27. }
28. }
29. if(in_array($zg_post_ID, $zg_cookiearray)){
30. $zg_key = array_search($zg_post_ID, $zg_cookiearray);
31. array_splice($zg_cookiearray, $zg_key,1);
32. }
33. array_unshift($zg_cookiearray, $zg_post_ID);
34. global $zg_number_of_posts;
35. while(count($zg_cookiearray)> $zg_number_of_posts){
36. array_pop($zg_cookiearray);
37. }
38. $zg_blog_url_array = parse_url(get_bloginfo('url'));
39. $zg_blog_url = $zg_blog_url_array['host'];
40. $zg_blog_url = str_replace('www.','', $zg_blog_url);
41. $zg_blog_url_dot ='.';
42. $zg_blog_url_dot .= $zg_blog_url;
43. $zg_path_url = $zg_blog_url_array['path'];
44. $zg_path_url_slash ='/';
45. $zg_path_url .= $zg_path_url_slash;
46. global $zg_cookie_expire;
47. setcookie("WP-LastViewedPosts-coding3min", serialize($zg_cookiearray),(time()+($zg_cookie_expire*86400)), $zg_path_url, $zg_blog_url_dot,0);
48. }
49.
50. function zg_recently_viewed(){
51. echo '<ul class="viewed_posts">';
52. if(isset($_COOKIE["WP-LastViewedPosts-coding3min"])){
53. $zg_post_IDs = unserialize(stripslashes($_COOKIE["WP-LastViewedPosts-coding3min"]));
54. foreach($zg_post_IDs as $value){
55. global $wpdb;
56. $zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");
57. foreach($zg_get_title as $zg_title_out){
58. echo "<li><a href=\"". get_permalink($value+0)."\" title=\"". $zg_title_out->post_title ."\">". $zg_title_out->post_title ."</a></li>\n";
59. }
60. }
61. }else{
62. }
63. echo '</ul>';
64. }
65.
66. add_action('get_header','zg_lwp_header');
然后在你的正文右边添加小工具:增强文本中插入以下代码。
-
1. <?php
2. if(function_exists('zg_recently_viewed')){
3. if(isset($_COOKIE["WP-LastViewedPosts-coding3min"])){
4. zg_recently_viewed();
5. }
6. }?
- >
效果图如下:
- 输入编号:6400,直达文章
- 输入m|M,直达目录列表