wordpress文章点赞功能目前已经相对普遍,很多插件和分享代码都自带此功能。而且样式各异足以满意wp小白用户的需要,但是如果想打造一款自己想要的点赞功能样式,还是要手动添加下代码才能实现。下面给大家推荐一种纯代码实现文章页面点赞的方法。用自定义字段保存赞数量,通过Cookies来禁止重复赞。
加入至Functions.php文件中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
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; } |
相对应的JS代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
$(document).ready(function() { $.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(); }); }); |
调用代码:
1 2 3 4 5 6 7 8 9 |
<div class="post-like"> <a href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>">喜欢 <span class="count"> <?php if( get_post_meta($post->ID,'bigfa_ding',true) ){ echo get_post_meta($post->ID,'bigfa_ding',true); } else { echo '0'; }?></span> </a> </div> |
参考CSS样式
1 2 3 4 |
.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} |
请引用版本为1.10或以上的jQuery。