Skip to content

Instantly share code, notes, and snippets.

@dkvadratu
Last active January 7, 2023 10:37
Show Gist options
  • Save dkvadratu/9932abacbb0b5e2ad697e182a461963b to your computer and use it in GitHub Desktop.
Save dkvadratu/9932abacbb0b5e2ad697e182a461963b to your computer and use it in GitHub Desktop.
{WP} AJAX call from URL
<?php
//example taken from https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/
//generate link
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id='.$post->ID.'&nonce='.$nonce);
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">vote for this article</a>';
//accept ajax action
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == ’) ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
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"]);
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment