欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」为WordPress正文添加最近看过功能教程

作者 : 自学哈 本文共2148个字,预计阅读时间需要6分钟 2022-11-26 共93人阅读
也想出现在这里? 联系我们

为了提高用户体验,方便读者知道自己最近阅读了哪些文章,让网站记住读者的浏览历史,今天就为大家分享为WordPress正文添加最近看过功能教程。

把下面的代码添加到主题目录下的functions.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-coding3min”])){

$zg_cookiearray = array($zg_post_ID);

}else{

$zg_cookiearray = unserialize(stripslashes($_COOKIE[“WP-LastViewedPosts-coding3min”]));

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-coding3min”, 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-coding3min”])){

$zg_post_IDs = unserialize(stripslashes($_COOKIE[“WP-LastViewedPosts-coding3min”]));

foreach($zg_post_IDs as $value){

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”;

}

}

}else{

}

echo ‘</ul>’;

}

add_action(‘get_header’,’zg_lwp_header’);

然后在你的正文右边添加小工具:增强文本中插入以下代码。

<?php

if(function_exists(‘zg_recently_viewed’)){

if(isset($_COOKIE[“WP-LastViewedPosts-coding3min”])){

zg_recently_viewed();

}

}?>

效果图如下:

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」为WordPress正文添加最近看过功能教程
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号