给wordpress的文章加上点赞功能
点赞功能实现其实很简单,不需要专门的插件,只需要下面的代码即可实现。用自定义字段保存赞数量,通过Cookies来禁止重复赞。
// 点赞
add_action('wp_ajax_nopriv_ality_ding', 'ality_ding');
add_action('wp_ajax_ality_ding', 'ality_ding');
function ality_ding(){
global $wpdb,$post;
$id = $_POST["um_id"];
$action = $_POST["um_action"];
if ( $action == 'ding'){
$bigfa_raters = get_post_meta($id,'ality_like',true);
$expire = time() + 99999999;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('ality_like_'.$id,$id,$expire,'/',$domain,false);
if (!$bigfa_raters || !is_numeric($bigfa_raters)) {
update_post_meta($id, 'ality_like', 1);
}
else {
update_post_meta($id, 'ality_like', ($bigfa_raters + 1));
}
echo get_post_meta($id,'ality_like',true);
}
die;
}
调用JS代码:
// 点赞
$.fn.postLike = function() {
if (jQuery(this).hasClass('done')) {
return false;
} else {
$(this).addClass('done');
var id = $(this).data("id"),
action = $(this).data('action'),
rateHolder = jQuery(this).children('.count');
var ajax_data = {
action: "ality_ding",
um_id: id,
um_action: action
};
$.post(wp_ajax_url, ajax_data,//wp_ajax_url为ajax提交URL,没调用的话直接改为/wp-admin/admin-ajax.php
function(data) {
jQuery(rateHolder).html(data);
});
return false;
}
};
$(document).on("click", ".favorite",
function() {
$(this).postLike();
});
调用时使用:
<span class="like">
<a href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" title="我赞" class="favorite<?php if(isset($_COOKIE['ality_like_'.$post->ID])) echo ' done';?>"><i class="icon-zan"></i>喜欢
<i class="count">
<?php if( get_post_meta($post->ID,'ality_like',true) ){
echo get_post_meta($post->ID,'ality_like',true);
} else {
echo '0';
}?></i>
</a>
</span>
注意:jQuery的版本必需在1.10以上。