非插件实现wordpress文章点赞功能

点赞插件不少,但做为一个代码狂,不习惯使用插件,这里介绍一种非插件实现点赞功能,通过ajax实时显示点赞数量,自定义字段保存赞数量,Cookies禁止重新点赞。
具体操作步骤
1、在当前主题functions.php文件中添加代码:

add_action('wp_ajax_nopriv_bigfa_like',?'bigfa_like');??
add_action('wp_ajax_bigfa_like',?'bigfa_like');??
function?bigfa_like(){??
????global?$wpdb,$post;??
????$id?=?$_POST["um_id"];??
????$action?=?$_POST["um_action"];??
????if?(?$action?==?'ding'){??
????????$bigfa_raters?=?get_post_meta($id,'bigfa_ding',true);??
????????$expire?=?time()?+?99999999;??
????????$domain?=?($_SERVER['HTTP_HOST']?!=?'localhost')???$_SERVER['HTTP_HOST']?:?false;?//?make?cookies?work?with?localhost??
????????setcookie('bigfa_ding_'.$id,$id,$expire,'/',$domain,false);??
????????if?(!$bigfa_raters?||?!is_numeric($bigfa_raters))?{??
????????????update_post_meta($id,?'bigfa_ding',?1);??
????????}else?{??
????????????update_post_meta($id,?'bigfa_ding',?($bigfa_raters?+?1));??
????????}?????
????????echo?get_post_meta($id,'bigfa_ding',true);??????
????}???????
????die;??
}??

2、在主题的footer.php文件的</body>前添加以下代码:


$(document).ready(function()?{
????$.fn.postLike?=?function()?{
????????if?($(this).hasClass('done'))?{
????????????alert('您已赞过本博客');
????????????return?false;
????????}?else?{
????????????$(this).addClass('done');
????????????var?id?=?$(this).data("id"),
????????????action?=?$(this).data('action'),
????????????rateHolder?=?$(this).children('.count');
????????????var?ajax_data?=?{
????????????????action:?"bigfa_like",
????????????????um_id:?id,
????????????????um_action:?action
????????????};
????????????$.post("/wp-admin/admin-ajax.php",?ajax_data,?function(data)?{
????????????????$(rateHolder).html(data);
????????????});
????????????return?false;
????????}
????};
????$(document).on("click",?".favorite",?function()?{
????????$(this).postLike();
????});
});

3、在当前主题的single.php文件的<?php the_content();?>代码下面添加点赞按钮调用代码:

4、在当前主题的style.css文件中添加点击按钮样式(仅供参考):


.post-like{text-align:center;padding:10px}
.post-like?a{?background-color:#21759B;border-radius:?3px;color:?#FFFFFF;font-size:?12px;padding:?5px?10px;text-decoration:?none;outline:none}
.post-like?a.done,?.post-like?a:hover{background-color:#eee;color:#21759B;}
.post-like?a.done{cursor:not-allowed}
© 版权声明
THE END
喜欢就支持以下吧
点赞0赞赏
分享
评论 抢沙发

请登录后发表评论