给 WordPress 文章添加点赞功能

点赞可以让读者对你文章的认可,目前大多数 WordPress 模板 都有点赞功能,如果你的模板还没有,手动来添加一个吧:

后台」→「外观」→「编辑」→ 「functions.php」文件,把下面的代码添加进去:

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;
}

后台」→「外观」→「编辑」→ 「footer.php」文件,把下面的代码添加进去:

<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">
         <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样式就完成了:

.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}

# 更多WordPress技巧,请关注「WordPress专题

方法来源:googlo