WordPress无刷新AJAX点赞功能

付费节点推荐


免费节点


节点使用教程


无插件点赞功能由 #Fatesinger# 提供,不过 @大发 好像删除了该篇文章。

实现原理大体是通过自定义字段保存赞数量,通过Cookie记录并禁止重复赞。

具体的代码如下:

演示网站:bizhi.bcoderss.com

function.php

[cc lang=”php”]
/**
* AJAX点赞
* by:bcoder.clbug.com
*
*/
function dotGood()
{
global $wpdb, $post;
$id = $_POST[“um_id”];
if ($_POST[“um_action”] == ‘topTop’) {
$specs_raters = get_post_meta($id, ‘dotGood’, true);
$expire = time() + 99999999;
$domain = ($_SERVER[‘HTTP_HOST’] != ‘localhost’) ? $_SERVER[‘HTTP_HOST’] : false; // make cookies work with localhost
setcookie(‘dotGood_’ . $id, $id, $expire, ‘/’, $domain, false);
if (!$specs_raters || !is_numeric($specs_raters)) update_post_meta($id, ‘dotGood’, 1);
else update_post_meta($id, ‘dotGood’, ($specs_raters + 1));
echo get_post_meta($id, ‘dotGood’, true);
}
die;
}
add_action(‘wp_ajax_nopriv_dotGood’, ‘dotGood’);
add_action(‘wp_ajax_dotGood’, ‘dotGood’);

add_filter( ‘manage_posts_columns’, ‘add_dotGood_columns’ );
add_action( ‘manage_posts_custom_column’, ‘output_dotGood_columns’, 10, 2 );
function add_dotGood_columns( $columns ){
// Add a new field
$columns[‘zan’] = __( ‘点赞’ );

// Delete an existing field, eg. comments
/* unset( $columns[‘comments’] );*/

return $columns;
}

function output_dotGood_columns( $column_name, $post_id ){
switch( $column_name ){
case “zan” :
// Retrieve data and echo result
$zan = get_post_meta( $post_id, ‘dotGood’, true );
echo $zan;
break;
}
}

[/cc]

JavaScript

[cc lang=”javascript”]
$.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: “dotGood”,
um_id: id,
um_action: action
};
$.post(“/wp-admin/admin-ajax.php”, ajax_data,
function (data) {
$(rateHolder).html(data);
});
return false;
}
};
$(“.dotGood”).click(function () {
$(this).postLike();
});
[/cc]

CSS

[cc lang=”css”]
.post-like{margin:10% 0 0;position:relative;}
.post-like a.dotGood{height:30px;line-height:30px;width:30px;font-size:24px;text-align:center;display:inline-block;cursor: pointer;position:relative;}
.post-like a.dotGood.done{color: #e2264d;}
.post-like a.dotGood span{position:absolute;display:inline-block;top:0;left:26px;width:auto;font-size:14px;}
.post-like a.dotGood span:before{content:’+’;}
[/cc]

HTML

[cc lang=”html”]

class=”dotGood “>



[/cc]

效果图

未经允许不得转载:Bcoder资源网 » WordPress无刷新AJAX点赞功能

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (19)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册