This simple tutorial teaches you how to make a voting counter using the post’s meta data.
I would like to know how to add down-votes to this small script (e.g. -1, -2).
In the following way: If the post has 0 votes and it gets down-voted, it ends up with -1. If the post has 1 vote and it is down-voted it ends up with 0 (only one counter).
the jQuery part:
<?php wp_enqueue_script( 'jquery' ) ?>
<?php wp_head(); ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".vote a").click(
function() {
var some = jQuery(this);
var thepost = jQuery(this).attr("post");
var theuser = jQuery(this).attr("user");
jQuery.post("<?php bloginfo('template_url'); ?>/vote.php", {
user: theuser,
post: thepost
}, function(data) {
var votebox = ".vote" + thepost + " span";
jQuery(votebox).text(data);
jQuery(some).replaceWith('<span class="voted">Voted</span>');
});
});
});
</script>
When a member clicks on the vote link,
the above code will get the post ID
and the memberâs user ID and send it
to a file called vote.php using a post
method. The vote.php file will perform
everything we need to add the vote.
vote.php:
<?php
$file = dirname(__FILE__);
$file = substr($file, 0, stripos($file, "wp-content") );
require( $file . "/wp-load.php");
$currentvotes = get_post_meta($_POST['post'], 'votes', true);
$currentvotes = $currentvotes + 1;
$voters = get_post_meta($_POST['post'], 'thevoters', true);
if(!$voters) $voters = $_POST['user']; else $voters = $voters.",".$_POST['user'];
update_post_meta($_POST['post'], 'votes', $currentvotes);
update_post_meta($_POST['post'], 'thevoters', $voters);
echo $currentvotes;
?>
Once the information is posted to
vote.php two custom fields are
created. One to count the vote and one
to add the voter to a list so that
they canât vote again.
functions.php:
// voting function
function voting($id) {
global $user_ID;
$currentvotes = get_post_meta($id, 'votes', true);
$voters = get_post_meta($id, 'thevoters', true);
$voters = explode(",", $voters);
foreach($voters as $voter) {
if($voter == $user_ID) $alreadyVoted = true;
}
if(!$currentvotes) $currentvotes = 0;
echo '<div class="vote vote'.$id.'"><span>'.$currentvotes.'</span>';
if($user_ID && !$alreadyVoted) echo '<br /><a post="'.$id.'" user="'.$user_ID.'">'.__("Vote").'</a>';
if($user_ID && $alreadyVoted) echo '<br /><span class="voted">'.__("Voted").'</span>';
echo '</div>';
if(!$user_ID) echo '<div class="signup"><p><a href="'.get_bloginfo('url').'/wp-login.php?action=register">'.__('Register').'</a> '.__('to vote').'.</p></div>';
}
any suggestions?
You will have to make a second button for down voting. Give the upvote button a class of up and the down vote button a class of down.
jQuery
vote.php
Thats all you should need to edit