当前位置: 首页 > wordpress分享 > 正文
无需插件纯代码三步实现wordpress文章点赞功能
发布:2018-01-26 15:26:09 分类:wordpress分享 2条评论
纯代码给wordpress文章增加点赞功能,首先说明,本段代码不是原创,原作者好像是bigfa;从代码中就可以看出来!为了方便自己使用,测试时做了一些调整,当然版权归原作者所有,wordpress点赞功能通过自定义字段保存赞数量,通过 cookies 来禁止重复赞。代码中可手动设置cookies过期时间,几次点击一次所增加的次数,本文中的赞大约有300多个是调整时自己点的,现在已经恢复正常!分享wordpress文章点赞代码如下:
首先在主题的function.php文件中添加以下内容:
- //赞
- add_action('wp_ajax_nopriv_bigfa_like', 'bigfa_like');
- add_action('wp_ajax_bigfa_like', 'bigfa_like');
- function bigfa_like(){
- $id = $_POST["um_id"];
- $action = $_POST["um_action"];
- if ( $action == 'ding'){
- $bigfa_raters = get_post_meta($id,'bigfa_ding',true);
- $expire = time() + 99999;
- $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;
- }
- //赞结束
添加JS代码到需要的页面,为了所有页面都能使用,尽可能添加到header.php或者footer.php,也可以将代码新建js文件,单独引用!
- <script type="text/javascript">
- $.fn.postLike = function() {
- if ($(this).hasClass('done')) {
- 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();
- });
- </script>
在文章页面single.php添加以下代码,代码放在你想出现点赞的地方,一般是文章内容<?php the_content(); ?>的下边,
- <div class="post-like">
- <div class="likebox"> <a href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>"> <img src="./images/like.png" /><div class="count">
- <?php if( get_post_meta($post->ID,'bigfa_ding',true) ){
- echo get_post_meta($post->ID,'bigfa_ding',true);
- } else {
- echo '0';
- }?>
- </div>
- </a>
- </div>
- </div>
其实上面的这些已经实现了wordpress文章点赞功能了,下面再美化一下点赞图标,把以下内容复制到主题的style.css中。
- /****点赞css***/
- .post-like{text-align:center;padding:10px;overflow:hidden}
- .likebox img{width:32px;height:32px}
- .post-like a.done{cursor:not-allowed}
- .likebox{margin:0 auto;width:100px;border-radius:10px;border:solid 1px #9CF;height:65px}
- .likebox:hover{background-color:#eee;color:#21759B;width:100px;height:65px;text-decoration:none}
- .count{color:red}
- .likebox a:hover{text-decoration:none}
- /***点赞css结束***/
如果你发现按照全文步骤下来,没有实现点赞的功能,或者点了之后不增加点赞数,那么很有可能是$.post("../wp-admin/admin-ajax.php", ajax_data,代码中引用的admin-ajax.php位置不对,再有可能就是你的wordpress版本低于4.4版本!
最活跃的读者