ajax更新wordpress静态页面的实时阅读量

技术控 Loading... 阅读

还是老样子,静态页面没有测试,我估计应该是可行的。在我印象里,我以前做过这种事情,当时好像第一次无效,之后刷新页面才有效果,找了不少资料,最后还是没有搞定,就放弃了。

需要两个页面:

ajax更新wordpress静态页面的实时阅读量

前台的ajax请求代码:

<!--更新浏览量-->
<?php if  (is_singular()) : ?>
<script language="javascript" type="text/javascript">
   $.ajax({
    url: "https://boke.slhq.cn/wp-content/themes/mkBlog/action/views.php" ,
    type: "post",
	async: false,
    loading: false,
    data: {"post_ID": <?php the_ID(); ?>},
    dataType: "json", 
    success: function(data, textStatus, xhr) {
        if (data.error){ return false;}else{
			$("#saonian").html(results.response);
		}
    }
   });
  </script>
<?php endif ; ?>

后台需要新建一个php文件来处理数据:

<?php
require( dirname(__FILE__).'/../../../../wp-load.php' );
nocache_headers();
$post_ID = isset($_POST['post_ID']) ? (int) $_POST['post_ID'] : 0;
if ($post_ID!=0 ) {
	$post_views = (int) get_post_meta($post_ID, 'views', true);
		if (!update_post_meta($post_ID, 'views', ($post_views + 1))) {
			add_post_meta($post_ID, 'views', 1, true);
		}
	$post_views = (int) get_post_meta($post_ID, 'views', true);
        print_r(json_encode(array('error' => 0, 'views' => 1, 'response' => $post_views)));
        exit;
}else{
	print_r(json_encode(array('error' => 1, 'views' => 0, 'response' => $post_views)));
        exit;
}

在我网站测试是失败的,刷新网页浏览数加两个,所以不管了,以后有需要静态化网站的时候再说吧。

Tags:

版权声明:若无特殊注明,本文皆为《书蓝画青》原创,转载务必保留文章来源。

本文链接:ajax更新wordpress静态页面的实时阅读量 & https://boke.slhq.cn/1327.html

推荐阅读
发表评论 取消回复
表情 图片 链接 代码

  1. 科华UPS电源蓄电池
    科华UPS电源蓄电池 Lv 1

    博主说的不错 支持

分享