I am trying to make a voting system for WordPress.

This is my code in functions.php:

  add_action("wp_ajax_add_votes_options", "add_votes_options");
  add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
   function add_votes_options() {
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce'))

$postid = $_POST['postid'];
$ip = $_POST['ip'];

$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
    echo "null";
} else {
    $voter_ips[] = $ip;
    update_post_meta($postid, "voter_ips", $voter_ips);

$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;

This is how I place my vote button and vote count button:

// This will display "0 votes" and increase as votes are added
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
if($votes == 1) $plural = ""; else $plural = "s";
echo '<div id="votecounter">'.$votes.' vote'.$plural.'</div>';

// This will display the vote button and disable it if a cookie has already
// been set. We also add the security nonce here. 
$hasvoted = $_COOKIE['better_votes'];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' class="disabled"';
} else {
$vtext = "VOTE";
$class = "";
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo   $vtext; ? ></a>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field ('voting_nonce', 'voting_nonce'); ?>

The problem is that it isn't updating the meta data. It shows 1 votes but doesn't update the meta data on click. I don't now what I am doing wrong.


The server-side code looks to be OK (at a glance) but you are not calling the correct server-side code from your JavaScript.

Have a look at this: http://wp.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress/. You need to have an Ajax call to admin-ajax.php?action=<your action>

  • Hello I figured out that post id is not coming properly – vaibhav Dec 19 '12 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.