Skip to content

Instantly share code, notes, and snippets.

@technosailor
Created February 8, 2012 17:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save technosailor/1771566 to your computer and use it in GitHub Desktop.
Save technosailor/1771566 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Test
*/
class My_Like_Button {
function __construct()
{
$this->hooks();
}
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' );
wp_print_scripts();
?>
<script>
jQuery(document).ready(function(){
jQuery('#like_this_post').click(function(){
var like_post_id = jQuery('#like_post_id').val();
var like_user_id = jQuery('#like_user_id').val();
jQuery.post(
'<?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) {
alert(response);
}
);
});
});
</script>
<?php
}
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" />
</form>';
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";
else
echo "Like recorded";
exit;
}
}
$my_like_button = new My_Like_Button;
@long-huo
Copy link

Nice article. THx

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