-
-
Save banago/1790188 to your computer and use it in GitHub Desktop.
Oboject Oriented WordPress Ajax API usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment