WordPress 高亮显示用户上次访问后新增的评论内容

如果一个用户对你的文章很感兴趣,他很可能会关注你文章的评论内容,那么我们如何让用户知道哪些评论内容是他上次访问后新增的呢,今天推荐的 Comments Since Last Visit 就可以做到这一点。

Comments Since Last Visit 是通过 Cookie 记录用户最后访问每篇文章的时间,然后对这个时间后的新增评论添加一个 CSS 类 及 对应的高亮样式。这样,用户下次过来(当然是同一个浏览器,没有清空 Cookie 的情况下),就可以很明显看到新增的评论内容了。

comments-since-last-visit_wpdaxue_com

你可以到作者博客下载该插件,或者下载本站备份

如果你不想弄插件,也可以试试倡萌根据插件源码整理出来的代码(未测试,欢迎反馈),添加到主题的 functions.php 即可:

/**
 * WordPress 高亮显示用户上次访问后新增的评论内容
 * https://www.wpdaxue.com/comments-since-last-visit.html
 */
add_action( 'get_header', 'wpdx_last_visit_cookie' );
function wpdx_last_visit_cookie()
{
	// 只对文章和页面这类页面生效
	if ( is_singular() )
	{
		// 获取当前文章的ID
		$id = get_the_ID();
		// 获取当前时间
		$current_time = strtotime( current_time( 'mysql' ) );
		// 查看是否 cookie 已经存在,如果是,获取 last_visit
		if ( isset( $_COOKIE['last_visit'] ) )
		{
			$latest_visit = json_decode( stripslashes( $_COOKIE['last_visit'] ), true );
			// 只保留最后 50 篇文章,防止cookie过大
			if ( count( $latest_visit ) >= 50 )
			{
				$latest_visit = array_diff( $latest_visit, array( min( $latest_visit ) ) );
			}
		}
		// 只保留这篇文章的 cookie 90天
		$latest_visit[$id] = $current_time;
		setcookie( 'last_visit', json_encode( $latest_visit ), time()+3600*2160 );
	}
}
add_filter( 'comment_class', 'wpdx_last_visit_comment_class' );
function wpdx_last_visit_comment_class( $classes )
{
	// 获取评论的时间
	$comment_time = strtotime( get_comment_date( 'Y-m-d G:i:s' ) );
	if ( isset( $_COOKIE['last_visit'] ) ) {
		$latest_visit = json_decode( stripslashes( $_COOKIE['last_visit']), true );
	}
	// 如果评论是用户上次访问之后新增的,就添加 new-comment 这个类
	if ( $comment_time > $latest_visit[get_the_ID()] )
	{
		$classes[] = 'new-comment';
	}
	return $classes;
}
// 添加高亮样式
add_action( 'wp_enqueue_scripts', 'wpdx_last_visit_styles' );
function wpdx_last_visit_styles()
{
	echo '<style>.new-comment { background-color: #f0f8ff; }</style>';
}

来源:

https://www.wpdaxue.com/comments-since-last-visit.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_33122.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?