wp系统并没有点赞的功能,要实现一个点赞功能,多少有点复杂,但是,跟着我的代码步骤,你想实现什么功能都ok,让我们一起giao~,废话不多说,看代码:

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

2.主题根目录添加main.js文件,加入

// 点赞js
$.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();
   });

3.页面引入jquery和main.js

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php bloginfo('template_url'); ?>'/main.js'"></script>

4.在页面中添加调用代码

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

5.style中加入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}

搞定收工个屁啊,累死了,发布了一天的文章...

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。