Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wpmu-authors/5b77823b65250637eee4396d8abcc5a0 to your computer and use it in GitHub Desktop.
Save wpmu-authors/5b77823b65250637eee4396d8abcc5a0 to your computer and use it in GitHub Desktop.
AJAX-Action-Hook-Plugin-Functions.php
<?php // used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("wp_ajax_my_user_like", "my_user_like");
add_action("wp_ajax_nopriv_my_user_like", "please_login");
// define the function to be fired for logged in users
function my_user_like() {
// nonce check for an extra layer of security, the function will exit if it fails
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_like_nonce")) {
exit("Woof Woof Woof");
}
// fetch like_count for a post, set it to 0 if it's empty, increment by 1 when a click is registered
$like_count = get_post_meta($_REQUEST["post_id"], "likes", true);
$like_count = ($like_count == ’) ? 0 : $like_count;
$new_like_count = $like_count + 1;
// Update the value of 'likes' meta key for the specified post, creates new meta data for the post if none exists
$like = update_post_meta($_REQUEST["post_id"], "likes", $new_like_count);
// If above action fails, result type is set to 'error' and like_count set to old value, if success, updated to new_like_count
if($like === false) {
$result['type'] = "error";
$result['like_count'] = $like_count;
}
else {
$result['type'] = "success";
$result['like_count'] = $new_like_count;
}
// Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
// don't forget to end your scripts with a die() function - very important
die();
}
// define the function to be fired for logged out users
function please_login() {
echo "You must log in to like";
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment