A Better Voting System for WordPress
I published a tutorial quite a while back called Simple Voting for WordPress with PHP and jQuery. It was not without its problems, and recently I needed to improve on it for a client, so I thought it would be a good idea to finally release an updated version.
The original tutorial relied on an outside PHP file to process the votes but now I use the built-in Ajax function in WordPress. That way it’s more secure and efficient. To get everything started, let’s take a look at the jQuery required:
<script type="text/javascript"> /* */ (function($) { $("#vote").not(".disabled").click(function() { var el = $(this); var nonce = $("input#voting_nonce").val(); var data = { action: 'add_votes_options', nonce: nonce, postid:'ID; ?>', ip:'REMOTE_ADDR']; ?>' }; $.post('admin-ajax.php'); ?>', data, function(response){ if(response!="-1") { el.html("VOTED").unbind("click"); if(response=="null") { alert("A vote has already been registered to this IP address."); } else { $("#votecounter").html(response); alert("Thanks for your vote."); } } else { alert("There was a problem registering your vote. Please try again later."); } }); return false; }); })(jQuery); /* */ script> |
If the vote button is clicked, it will send the Ajax request and process it accordingly, depending on a few things. The only thing missing, is the code to register a cookie once the vote has been calculated so that voters can only vote once. Let’s include two cookie functions originally created by Peter-Paul Koch and add a block of code to our original script:
<script type="text/javascript"> /* */ (function($) { function setCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = “; expires=”+date.toGMTString(); } else var expires = “”; document.cookie = name+“=”+value+expires+“; path=/”; } |







