文章AJAX點贊的功能實現原理
通過自訂欄位儲存贊數量,通過cookies來禁止重複贊.
WordPress不用外掛程式來實現文章AJAX點贊的操作過程
我們直接將下面的代碼加入到你的當前主題的 functions.php 中,內容如下:
add_action('wp_ajax_nopriv_specs_zan', 'specs_zan');
add_action('wp_ajax_specs_zan', 'specs_zan');
function specs_zan(){
global $wpdb,$post;
$id = $_POST["um_id"];
$action = $_POST["um_action"];
if ( $action == 'ding'){
$specs_raters = get_post_meta($id,'specs_zan',true);
$expire = time() + 99999999;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; // make cookies work with localhost
setcookie('specs_zan_'.$id,$id,$expire,'/',$domain,false);
if (!$specs_raters || !is_numeric($specs_raters)) {
update_post_meta($id, 'specs_zan', 1);
}
else {
update_post_meta($id, 'specs_zan', ($specs_raters + 1));
}
echo get_post_meta($id,'specs_zan',true);
}
die;
}
然後在您的當前主題的footer.php檔案中加入以下代碼,這裡部落說明一下,是加入js代碼:
$.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: "specs_zan",
um_id: id,
um_action: action
};
$.post("/wp-admin/admin-ajax.php", ajax_data,
function(data) {
$(rateHolder).html(data);
});
return false;
}
};
$(document).on("click", ".specsZan",
function() {
$(this).postLike();
});
再接下來,我們在你想顯示的地方加入如下代碼,推薦加到文章內容尾部.
<div class="post-like">
<a href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="specsZan <?php if(isset($_COOKIE['specs_zan_'.$post->ID])) echo 'done';?>">喜歡 <span class="count">
<?php if( get_post_meta($post->ID,'specs_zan',true) ){
echo get_post_meta($post->ID,'specs_zan',true);
} else {
echo '0';
}?></span>
</a>
</div>
最後,當然是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}
到此,所有過程走完,自己去看看效果吧.