Simple Voting for WordPress with PHP and jQuery

This tutorial is no longer up-to-date. Please check out A Better Voting System for WordPress for a more secure and efficient approach.

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 '
'.__("Vote").''; if($user_ID && $alreadyVoted) echo '
'.__("Voted").''; echo '
'; if(!$user_ID) echo ''; }

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:

0
Vote

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie