I needed to create a simple way for site members to vote on a post and the few scripts I found didn’t really work how I needed them to. So I decided to whip something together myself. I developed a pretty basic script using PHP and jQuery to allow members who are signed in to click on a simple link to add their vote to a post.
First you need to add this to your header.php
file between the <head> tags. If you notice that you already have the <?php wp_head(); ?>
call somewhere else in your header.php
file, just delete it.
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.
So let’s create a file called vote.php
and add it to your theme’s directory.
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.
Add the code below to your functions.php
file, or create a functions.php
file if your theme does not have one.
// 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 ''.$currentvotes.''; if($user_ID && !$alreadyVoted) echo ''; if(!$user_ID) echo '
'.__("Vote").''; if($user_ID && $alreadyVoted) echo '
'.__("Voted").''; echo ''; }'.__('Register').' '.__('to vote').'.
Let’s add some CSS to style our voting box.
.vote { padding: 5px 0; background: #eee; border: 1px solid #ddd; width :50px; text-align: center; margin: 10px auto; } .vote a, .vote span.voted { cursor: pointer; margin-top: 5px; padding-top: 5px; border-top: 1px solid #ddd; display: block; } .vote span.voted { cursor: default; }
Now all you need to do is add the following within the WordPress loop to have the voting box appear.
ID); ?>
Test it out below: