I’m trying to create a voting system for my WordPress blog, but the code I’ve written does not update the metadata field created for the votes and each time i call the function to add a vote I get the value 1 returned,
Here is the code I’ve written:
First in the html part of the post I’ve created a link which calls the loadurl() via javascript:
<a onclick="loadurl()" class='voteup' title="ب٠اÛ٠پست Û٠اÙ
تÛاز"><i class="icon-angle-up"></i></a>
the script for the loadurl() call is as below which uses ajax to call the call_me() function from the functions.php file
function loadurl() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var value = $.ajax({
type: "POST",
url: ajaxurl,
data:{
//the call_me function for adding a vote in the functions.php
action: 'call_me'
}
})
.fail(function(r,status,jqXHR) {
console.log('failed');
})
.done(function(r,status,jqXHR) {
console.log('success');
//r is the return value of the function call_me();
console.log(r);
});
}
and finally in the functions.php file I’ve added an action hook (which i’m not really certain about) and the function body who is supposed to get the currentvotes and after adding 1 to the current vote update it as the new vote count:
<?php
add_action('wp_ajax_noPriv_call_me', 'call_me');
add_action('wp_ajax_call_me', 'call_me');
add_action('save_post', 'call_me');
function call_me() {
global $wpdb;
$currentvotes = get_post_meta($_POST['post'], 'votes', true);
$currentvotes = $currentvotes + 1;
update_post_meta($_POST['post'], 'votes', $currentvotes);
echo $currentvotes;
die();
}
?>
but the currentvotes value outputed from the console.log(r) function in the loadurl() functions is always 1,
The problem was that I wasn’t passing the PostID to the callme() function and for some reason wasn’t able to get the postID once I was inside the php function in functions.php.
So I added the id variable which stored the postID in it:
and then passed it to the callme() function by adding the following to the ajax call:
so now the ajax call looks something like this:
now with
$id= $_REQUEST['id'];
I can retrieve the postID from which the Ajax call was made and with the following function I can read the vote value from the corresponding metadata stored for the post and return it to the ajax call: