Skip to content

程序员灯塔

Menu
  • Download
  • sitemap
  • 文章归档
  • 标签归档
  • 示例页面
Menu

wordpress ajax方法示例, 增加文章阅读次数

Posted on 2017 年 7 月 27 日

functions.php

 

function setPostViews($postID) {
$count_key = ‘post_views_count’;
$count = get_post_meta($postID, $count_key, true);
if($count==”){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}

//ajax 增加文章阅读量
function myviews12(){
$post_id = $_REQUEST[‘postid’];
setPostViews($post_id);
echo 1;

}
add_action(‘wp_ajax_myviews’, ‘myviews12’);

 

 

single.php

 

<?php $admin_url=admin_url( ‘admin-ajax.php’ );?>
<script type=”text/javascript”>
$(document).ready(function(){
//ajax 增加阅读次数
$.ajax({
//后台根据action返回相应数据
url: “<?php echo $admin_url;?>?action=myviews&postid=<?php echo get_the_ID(); ?>”,
type: ‘get’,
beforeSend: function() {
// 可以显示loading
},
error: function(error) {
// 错误处理
},
success: function(data) {
// 成功返回数据,先清空初始标签,装载新数据淡入
//console.info(data);
}
});
});

近期文章

  • 技术网站
  • 世界,您好!
  • Git学习记录(learngitbranching.js.org)
  • 阿里职场潜规则
  • 寻找两个正序数组的中位数

近期评论

  1. 一位 WordPress 评论者 发表在 世界,您好!

归档

  • 2024 年 9 月
  • 2024 年 3 月
  • 2022 年 12 月
  • 2021 年 8 月
  • 2021 年 6 月
  • 2021 年 3 月
  • 2021 年 2 月
  • 2020 年 11 月
  • 2020 年 5 月
  • 2020 年 3 月
  • 2019 年 11 月
  • 2019 年 10 月
  • 2019 年 9 月
  • 2019 年 7 月
  • 2019 年 6 月
  • 2019 年 5 月
  • 2019 年 3 月
  • 2018 年 9 月
  • 2018 年 8 月
  • 2018 年 7 月
  • 2018 年 4 月
  • 2018 年 2 月
  • 2018 年 1 月
  • 2017 年 12 月
  • 2017 年 11 月
  • 2017 年 10 月
  • 2017 年 8 月
  • 2017 年 7 月

分类目录

  • 未分类
©2025 程序员灯塔 | Design: Newspaperly WordPress Theme