Implementing WordPress Article Like Functionality Using Code

Publish: 2020-03-30 | Modify: 2020-03-30

To achieve better interactive effects, the Msimple theme has been upgraded recently to add a like function for articles. This function refers to an article on Chuangkeyun: Pure Code WordPress Article Add Like Function. Here I record and share it.

Implementation Idea

Real-time display of the number of likes through AJAX, custom fields to save the number of likes, and cookies to prevent re-liking.

Add Code

Add the following code to the functions.php file of the theme:

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

Add the following code to the footer.php file of the theme. This code depends on jQuery, so make sure you have included jQuery before using it:

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

Modify the single.php file of the article page and add a like button at the desired location. The code is as follows:

<a href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>" class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>">Like <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>

By using the above three code snippets, the article like function has been implemented. However, the style effect is not good. The author also provides the following style, which can be added to the style.css of the theme (the xiaoz style below has not been tested):

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

However, the style of each theme may be different, and the above CSS style may not be suitable. It is recommended to write CSS styles based on your own theme style (requires certain front-end knowledge).

Improvement

The above method changes the class attribute by judging whether the COOKIE exists in PHP, and then judges whether the button can be clicked. But if your website uses a CDN or uses static caching plugins like WP-Super-Cache, the page will be cached in advance, and the judgment will fail, allowing unlimited likes. Therefore, xiaoz has made improvements, and a second judgment of COOKIES is made through JS. The code is as follows.

Add the following code to the appropriate location in the single.php file of the theme:

<a id="praise" data-no-instant class="favorite<?php if(isset($_COOKIE['bigfa_ding_'.$post->ID])) echo ' done';?>" href="javascript:;" data-action="ding" data-id="<?php the_ID(); ?>"><i class="fa fa-thumbs-o-up"></i> Like <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>

Add the following code to the footer.php file at the bottom of the theme (depends on jQuery):

<script type="text/javascript">
// Get cookie
function getCookie(cookieName){  
    var cookieValue="";  
    if (document.cookie && document.cookie != '') {   
        var cookies = document.cookie.split(';');  
        for (var i = 0; i < cookies.length; i++) {   
             var cookie = cookies[i];  
             if (cookie.substring(0, cookieName.length + 2).trim() == cookieName.trim() + "=") {  
                   cookieValue = cookie.substring(cookieName.length + 2, cookie.length);   
                   break;  
             }  
         }  
    }   
    return cookieValue;  
}
$.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);
            $("#praise").removeClass("layui-btn-danger").addClass("layui-bg-gray");
        });
        return false;
    }
};
$(document).on("click", ".favorite",
function() {
    var post_id = $("#praise").attr("data-id");
    // Get COOKIE
    if ( getCookie('bigfa_ding_' + post_id) != '' ){
        alert('You have already liked it!');
    }
    else{
        $(this).postLike();
    }
});
</script>

Summary

Finally, a similar like effect to xiaoz's blog post is achieved. Here, I mainly provide ideas and code implementation. You need to adjust and modify the code according to your own situation. It should be easy for developers.

Some content in this article is referenced from: https://www.22vd.com/44000.html


Comments