I hope you are doing well. Here, I am sharing code for recording likes. The code for single.php
have the javascript code for making an ajax call to a wp function. This wp function have the code to store like expressions and it will return you the total number of like expressions recorded on post.
I have curated it for only the Logged in users.
Place this code in your functions.php
/* Ajax call */
add_action('wp_ajax_likeExpression', 'likeExpression');
function likeExpression() {
if(is_user_logged_in()){
$post_id = $_GET['post_id'];
$userId = get_current_user_id();
$metaKey = '_like_on_game_post_';
$userLikes = get_user_meta($userId, $metaKey, true);
if(empty($userLikes)){
update_user_meta($userId, $metaKey, wp_json_encode([$post_id]));
}else{
$userLikes = json_decode($userLikes);
if(!in_array($post_id, $userLikes)){
array_push($userLikes, $post_id);
update_user_meta($userId, $metaKey, wp_json_encode($userLikes));
}
}
$postLikeCount = get_post_meta($post_id, '_like_count_on_post_', true);
update_post_meta($post_id, '_like_count_on_post_', ++$postLikeCount);
exit($postLikeCount);
}
}
Place this in single.php, (before footer ends)
<?php if(is_user_logged_in()): ?>
<script>
jQuery(function($){
$('.game-footer-like-btn').on('click', function(){
$.ajax({
url: '<?php echo admin_url('admin-ajax.php?action=likeExpression&post_id='.get_the_ID()) ?>',
method: 'get',
}).done(function(res){
console.log(res)
//if its done
});
});
});
</script>
<?php endif; ?>
Please, feel free to contact if you any query.
Thank You 🙂