Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Like & Dislike functionality using JavaScript

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 🙂

Related Posts:

  1. Content hooks vs User hooks
  2. Job of meta_key meta_value fields in database tables
  3. get_*_meta doesn’t always return an array
  4. Retrieve user_meta and copy to post_meta
  5. Array of user ids to list of user names
  6. get Insert id for meta field
  7. help to decipher wp metadata
  8. Check For get_post_meta on Author Archive Page
  9. show user based on user_meta
  10. How do I retrieve the slug of the current page?
  11. How to extract data from a post meta serialized array?
  12. How to save an array with one metakey in postmeta?
  13. WordPress is stripping escape backslashes from JSON strings in post_meta
  14. Lack of composite indexes for meta tables
  15. Trying to get custom post meta through Jetpack JSON API [closed]
  16. Why time functions show invalid time zone when using ‘c’ time format?
  17. Why is get_post_meta returning an array when I specify it as single?
  18. Save both current and new version of post meta
  19. WP REST API “rest_no_route” when trying to update meta
  20. get_post_meta – get a single value
  21. What action hook updates post meta?
  22. get_post_meta / update_post_meta array
  23. How do I access post meta data when publishing a new post in Gutenberg?
  24. Triple meta_key on custom SELECT query
  25. update_post_meta not adding anything.(Nor add_post_meta)
  26. Are multiple values from get_post_meta guaranteed to be ordered?
  27. Identifying Importer Posts
  28. How metadata API works?
  29. How to sanitize post meta field value?
  30. WordPress Action Hooks and Post ID?
  31. Post IDs missing on delete_postmeta action hook
  32. How trigger to save post when updating post meta
  33. Create a Metabox that behaves Like a Taxonomy Box
  34. Views count with time limit per IP
  35. Is it possible to store visitors IPs in wp_postmeta table?
  36. order by multiple meta_keys?
  37. Custom meta field don’t give me numerical value
  38. echo image caption
  39. Generate multiple goo.gl shortlinks for qtranslate bilingual blog
  40. Creating user status mode in WordPress
  41. How can I convert postmeta from unserialized to serialized?
  42. Saving repeated option values when querying in Published, draft and all
  43. How to hide meta block(s) in certain post format
  44. Is there a way to append meta data without creating a race condition?
  45. add_post_meta adds meta to one more different post
  46. Custom query, multiple custom keys
  47. Trying to get property of non-object error using get_post_meta()
  48. how to get a list of meta data fields assocaited with a custom post type
  49. Gutenberg: How to display meta field data in the block frontend (save function)
  50. String taken from database table post_meta is showing HTML tags on Frontend
  51. Delete posts based on post meta data
  52. Query posts WITHOUT a custom meta field
  53. get_post_meta not working when variable used for post ID
  54. How do I edit the posted “by” and “on” in the post meta
  55. How to delete duplicate records in wp_postmeta database table?
  56. update_post_meta() adding bits in database [closed]
  57. Get posts ordered by meta data
  58. Displaying values from related field – if empty shows current post type’s link and title
  59. get_post_meta inside echo [closed]
  60. WordPress postmeta: Store data as an array or single item?
  61. Display Post Meta in Header
  62. Conditional For get_the_author_meta
  63. Custom fields or something else
  64. Is there a way combine posts meta_name?
  65. Compare User meta_value with Product meta_value
  66. I want to Add Feedburner Right After Meta Details
  67. if get_post_meta function returns empty – Do Not Display HTML
  68. Custom column on CPT not showing correct value when meta data not set
  69. How to access post meta on the first time a post is published
  70. Removing Malware
  71. I Can’t get the post_tag name from term_id using wp_set_object_terms
  72. After updating the custom post type, metafields disappear from the post.php edit menu, how do I fix it?
  73. Creating a custom post type upon registration for a specific user role
  74. URL from get_post_meta() is broken my URL
  75. How to update/add child posts meta whenever the parent post meta is updated?
  76. How to query post with meta?
  77. why is my postmeta table is so heavy
  78. update_post_meta() throws Uncaught error: Cannot create duplicate attribute
  79. Using a comma instead of a pipe to separate metadata
  80. Meta keys won’t add using wp_insert_post
  81. How Can I extract Image urls from post meta
  82. Retrieve posts from meta key
  83. Assign postmeta in bulk
  84. Twenty Twelve entry meta data – change and move
  85. Re-order posts inside tax query
  86. How can I prevent the post_modified column in wp_posts from being updated?
  87. wordpress simple post multi rating with post_meta and user_meta
  88. Sorting meta box values by start- and enddate and all dates in between
  89. Use an id on a button to update_post_meta in post
  90. Using mysql queries to delete custom post types based on meta_value
  91. get_post_meta image width for lazy load
  92. Write query according to post_meta
  93. Custom Fields help
  94. WP-API : post_meta not updated… but have another entry
  95. Parse error thrown by get_post_meta [closed]
  96. How to get all the related ids without array?
  97. Remove action of an external plugin after checking if custom post meta is set
  98. I am stuck between post meta function to call unique id
  99. Cannot read properties of undefined (reading ‘useEntityProp’)
  100. Add specific postmeta to search query
Categories post-meta Tags post-meta, user-meta
Shipping methods in dropdown instead of radio buttons [closed]
How to let user store a file in plugin directory but not have it get deleted on update?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress