WordPress 通过ajax处理自定义过程

背景:页面通过cloudflare静态化缓存了,但是后台需要获取页面的访问数。

解决方法:

主题的functions.php 添加以下代码:

function addviews(){
if($_GET[‘id’]){
$count_key = ‘post_views_count’;
$count = get_post_meta($_GET[‘id’], $count_key, true);
if($count==”){
$count = 0;
delete_post_meta($_GET[‘id’], $count_key);
add_post_meta($_GET[‘id’], $count_key, ‘0’);
}else{
$count++;
update_post_meta($_GET[‘id’], $count_key, $count);
}
}
wp_die();
}
add_action( ‘wp_ajax_addviews’, ‘addviews’ );
add_action( ‘wp_ajax_nopriv_addviews’, ‘addviews’ );

 

在主题的single.php添加以下代码:

<script type=’text/javascript’>!function(){var o=”<?php echo admin_url(‘admin-ajax.php’)?>?action=addviews&id=<?php echo get_the_ID();?>&t=” + new Date().getTime();var i=new Image;i.src=o}();</script>