Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Plugin Name: Test
class My_Like_Button {
function __construct()
function hooks()
add_action( 'wp_head', array( $this, 'js' ) );
add_action( 'wp_ajax_register_like', array( $this, 'handle_like' ) );
function js()
wp_enqueue_script( 'jquery' );
var like_post_id = jQuery('#like_post_id').val();
var like_user_id = jQuery('#like_user_id').val();
'<?php echo get_option('siteurl') . '/wp-admin/admin-ajax.php' ?>',
action : 'register_like',
user_id : like_user_id,
post_id : like_post_id,
_wpnonce : '<?php echo wp_create_nonce('nonce-register_like'); ?>',
function(response) {
function like_button()
if( !is_user_logged_in() )
return false;
global $current_user;
$html = '<form action="" method="post">
<input type="hidden" name="like_post_id" id="like_post_id" value="' . get_the_ID() .'">
<input type="hidden" name="like_user_id" id="like_user_id" value="' . $current_user->ID . '">
<input type="button" name="like_this_post" id="like_this_post" value="Like" />
return $html;
function handle_like()
global $wpdb;
$user_id = (int) $_POST['user_id'];
$post_id = (int) $_POST['post_id'];
if( !is_user_logged_in() )
return false;
if( !wp_verify_nonce( $_POST['_wpnonce'], 'nonce-register_like' ) )
die( 'Go away, asshole!' );
Here is where we do some sort of database operation to associate
the Like of the given post with the user who performed the action
Make sure you check for errors. In order to return data, you must
echo something that the originating page can see. True or false
only makes sense on this page and not back there.
Typically, you'd output some sort of JSON, XML or plain text.
$meta_id = add_post_meta( $post_id, 'user_liked', $user_id );
if( !$meta_id )
echo "Like not recorded";
echo "Like recorded";
$my_like_button = new My_Like_Button;
Copy link

clarklab commented Feb 9, 2013

This is deliciously perfect. I've been stringing it together for a few years now but it's nice to have it all in one place to reference the 'right way' that often gets lost in my copy/paste/copy/paste between builds.

Copy link

long-huo commented Dec 30, 2013

Nice article. THx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment