WordPress支持CDN的文章阅读计数

思路:使用Ajax自动提交请求增加文章阅读数,Cookie记录是否已经提交,避免刷新重复提交。

JS代码(保存为views.js):

//获取Cookie
function getCookie(name) {
	var str = document.cookie;
	var arr = str.split('; ');
	for(var i=0; i<arr.length; i++) {
		var c = arr[i].split('=');
		if(c[0] == name) {
			return c[1];
		}
	}
	return false;
}
//Ajax请求
function setPostmeta(varname, postid, target) {
	var cookie = getCookie(varname);
	if(cookie) return;
	jQuery.ajax({
		cache: false,
		url: ajax_object.ajax_url,
		type: 'POST',
		data: {
			'action': 'add_views',
			'post_id': postid,
		},
		dataType: 'JSON',
		async: true,
		success:function(result) {
			if(result.status == 'success') {
				if(target) target.text(result.views);
				var exdate = new Date();
				exdate.setDate(exdate.getDate() + 360);
				document.cookie = varname + '=' + result.views + '; expires=' + exdate.toGMTString() + '; path=/';
			}
		}
	});
}

functions.php中添加如下代码:

//加载JS以及设置Ajax对象
function bzg_load_scripts() {
	if(!is_single()) return;
	wp_enqueue_script('views', get_theme_file_uri('/js/views.js'), 'jquery');
	wp_localize_script('views', 'ajax_object', array(
		'ajax_url' => admin_url('admin-ajax.php')
	));
}
add_action('wp_enqueue_scripts', 'bzg_load_scripts');

//获取文章阅读数
function bzg_post_views($postid='') {
	global $post;
	if(!$postid && isset($post->ID)) {
		$postid = $post->ID;
	}
	if(!$postid) return 0;

	$views = get_post_meta($postid, 'views', true);
	echo $views ? $views : 0;
}

//Ajax添加阅读数
function bzg_set_post_views() {
	if(!isset($_POST['post_id'])) return;
	$post_id = (int) $_POST['post_id'];
	if(get_post_status($post_id) === false) return;

	$views = get_post_meta($post_id, 'views', true);
	if(!$views) $views = 0;
	$views = $views+1;
	update_post_meta($post_id, 'views', $views);

	wp_send_json(array(
		'status' => 'success',
		'views' => $views,
	));
}
add_action('wp_ajax_add_views', 'bzg_set_post_views');
add_action('wp_ajax_nopriv_add_views', 'bzg_set_post_views');

single.php中调用JS函数:

<script type="text/javascript">
	var target = jQuery(".views");
	var post_id = <?php echo $id; ?>;
	setPostmeta("views_" + post_id, post_id, target);
</script>

target是显示文章阅读数的标签,在需要显示文章阅读数的地方这样调用:

<span class="views">阅读:<?php bzg_post_views(); ?></span>

缺点是最新的阅读数不能实时显示,毕竟CDN缓存了页面,不过计数是正常写入到数据库的。

未经允许不得转载:主题君 » WordPress支持CDN的文章阅读计数
赞(296)

账号密码登录