Skip to content

Instantly share code, notes, and snippets.

@SalmanRavoof
Created August 9, 2019 03:23
Show Gist options
  • Save SalmanRavoof/390047edf4d51bc00eb1bdbb6d312107 to your computer and use it in GitHub Desktop.
Save SalmanRavoof/390047edf4d51bc00eb1bdbb6d312107 to your computer and use it in GitHub Desktop.
Add this code to your theme's post template to have it prepared for making an Ajax call, with or without JavaScript enabled on the client side.
// The 'likes' meta key value will store the total like count for a specific post, it'll show 0 if it's an empty string
<?php
$likes = get_post_meta($post->ID, "likes", true);
$likes = ($likes == "") ? 0 : $likes;
?>
This post has <span id='like_counter'><?php echo $likes ?></span> likes<br>
// Linking to the admin-ajax.php file. Nonce check included for extra security. Note the "user_like" class for JS enabled clients.
<?php
$nonce = wp_create_nonce("my_user_like_nonce");
$link = admin_url('admin-ajax.php?action=my_user_like&post_id='.$post->ID.'&nonce='.$nonce);
echo '<a class="user_like" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">Like this Post</a>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment