wordpress 添加文章点赞功能

yahoojapan 2019-2-17 3665

实现原理

通过自定义字段保存赞数量,通过 cookies 来禁止重复赞。

然后需要添加些代码实现此功能,下面一一列出。

1、将下面代码添加进function.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;
}

2、将以下代码扔进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>

3、修改single.php文件,在你想要添加的地方,加入下列代码:

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


最新回复 (0)
全部楼主
返回