Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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'))
    return;

$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";
    die(0);
} 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;
die(0);
    }

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

    <?php
// 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>';
?>

<?php
// 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.

share|improve this question

1 Answer 1

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>

share|improve this answer
    
Hello I figured out that post id is not coming properly –  vaibhav Dec 19 '12 at 5:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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