1

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.

1 Answer 1

0

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>

1
  • Hello I figured out that post id is not coming properly Commented Dec 19, 2012 at 5:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.