Adding a likes count with thumbs up icon is quite easy without using a plugin. Below I explain the code I used here in my website. All the code explained goes in the functions.php file in the theme, although it can be modified to use in a plugin as well.
Functionality
What we are going to do is store likes count in post meta of whichever the post you choose to add a likes count to. The post meta field name will be “likes”. Whenever the thumbs-up icon is clicked, the likes count will increment. We are not tracking if a user has already liked an article with this method. However that can be done using cookies. We will use a simple shortcode that can be placed where ever in the site we want to show the likes count button.
FYI, the shortcode is using GLOBAL $post variable to get the post ID. And the post ID will be whatever is in the global post value within a wp query loop.
Pre-rec Libraries I am using
I am using the free and always awesome fontawesome library to get the thumbs up icon. Aside that, jQuery library which is a standard load on most websites these days.
Adding Likes Button Shortcode
This will allow the functionality for shortcode [aj_likes_btn] the context of which you can edit for your liking. This shortcode will print the HTML code where ever the shortcode is placed, to display a thumbs-up icon button and likes count.
<?php add_shortcode('aj_likes_btn', 'aj_likes_btn'); function aj_likes_btn(){ global $post; $post_id = $post->ID; $current_count = get_post_meta( $post_id, 'likes',true); $current_count = $current_count ? $current_count : 0; ob_start(); ?> <div class='aj_likes'> <p><a class='aj_thumbsup' href='' data-id='<?php echo $post_id;?>'> <i class="far fa-thumbs-up"></i></a> Likes (<span><?php echo $current_count;?></span>)</p> </div> <?php return ob_get_clean(); }
Adding AJAX functionality
This JQuery code can be added to existing javascript file ( in which case the AJAX url must be updated to correct ajax url) or save into a new javascript file called aj_script.js
jQuery(document).ready(function($){ $('body').on('click','.aj_thumbsup',function(event){ event.preventDefault(); // stop click from refreshing page var OBJ = $(this); if(OBJ.hasClass('recorded')) return; // stop multiple submissions var id = $(this).data('id'); // get post ID var data_arg = {}; data_arg['id'] = id; data_arg['action'] = 'aj_like_post'; // ajax hook name $.ajax({ beforeSend: function(){}, type: 'POST', url:the_ajax_script.ajaxurl, // Must be updated if adding this to existing data: data_arg,dataType:'json', success:function(data){ OBJ.siblings('span').html( data.new_count); // populate with new new_count OBJ.addClass('recorded') // mark as thumbsup recorded OBJ.find('i').removeClass('far').addClass('fas'); // make thumbs up icon solid } }); }); });
To enqueue the above script use this PHP code, which goes into function.php. Make sure to replace THEME_DIR with correct location if you are saving the javascript code to a different location.
<?php define("THEME_DIR", get_template_directory_uri()); wp_enqueue_script( 'aj_script', THEME_DIR . '/aj_script.js', array( 'jquery' ), 1.0, true ); wp_localize_script( 'aj_script', // the handle name of the script 'the_ajax_script', apply_filters('aj_script_data', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) , 'postnonce' => wp_create_nonce( 'aj_nonce' ) )) );
PHP code to process the AJAX request which would record the new incremented like count for the post.
<?php add_action( 'wp_ajax_aj_like_post', 'aj_record_like_post' ); add_action( 'wp_ajax_nopriv_aj_like_post', 'aj_record_like_post' ); // nopriv allows for nonloggedin users to like as well public function aj_record_like_post(){ $post_id = sanitize_text_field( $_POST['id']); $current_count = get_post_meta( $post_id, 'likes',true); $current_count = $current_count ? $current_count : 0; $new_count = $current_count + 1; // add one more like update_post_meta( $post_id, 'likes', $new_count); // save new count to the post meta echo json_encode(array( 'status'=>'good', 'new_count'=>$new_count, )); exit; }
CSS code to stylize the looks.
.aj_likes{text-align:center; padding:30px 0; font-size:18px;} .aj_likes a:hover i{transform: scale(1.2);} .aj_likes a.recorded:hover i{transform: scale(1);}
Now add the shortcode [aj_likes_btn] where ever you want viewers to like that post, and it will look like this on the post. If you like this code share, be sure to give my like button a smashing as well 🙂
5 years ago
34 Books I Read or Listened to in 2020
In 2020 I got the chance to explore more into the non-fiction category of books. I went from personal improvement and explorative genre to more philosophical genre. I found the…
5 years ago
CODE: How to check if a customer used a coupon in Woocommerce
Situation: We have a coupon code (Free $5 cash) that we want customers to use one time. Until he use it, show a special message on my account. After he…
5 years ago
My work today will be dwarfed by my work tomorrow
When I write code, develop algorithms or programs, I do them to the fullest of my skills - with all I know. Once I wrap things up, I know I…
5 years ago
When all I can breath is wildfire smoke
Wildfire Smoke 2 weeks ago Oregon had a bad wildfire spread from multiple wildfires, burning about 200k-300k acres of forests. In my time in Oregon, this is the second bad…
5 years ago
Lessons from Nansen Summit
Nansen Summit is the summit of Mount Sylvalia that is close to where I live, with an elevation of just shy of 1000ft. Only after living here 2 years, I…
5 years ago
What if all the people realized they don't need stuff to be happy tomorrow
US economy and the global economy -for the best part- is run by consumers. And these consumers empower big corporations to exists. This whole so called economic system created by…
6 years ago
Valley of Lauterbrunnen
Lauterbrunnen valley in Switzerland is one of the best places I have been to where you can easily find the nature at its best display. This painting is from my…
6 years ago
Making of The Männlichen Painting
Switzerland is just breathtaking and every where you turn up in the great alps, is just another view worth painting. The painting of Männlichen is based on a photo i…
6 years ago
Welcome 2020 - The existence of this site
Hello everyone I am Ashan Jay. I am not an extraordinaire or a smart genius, I am just an average guy who falls just like everyone else but learn from…
6 years ago
Books I have read or listened in 2019
A complaint free world by Will Bowen The magic of thinking big by David Schwartz It works by RHJ 12 Rules for life by Jordan Paterson Radical Acceptance by Tara…