Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9063763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:05:19+00:00 2026-06-16T16:05:19+00:00

I am making a voting system for my theme It is working fine in

  • 0

I am making a voting system for my theme

It is working fine in single.php

But when i keep it in index.php it only considers the id of first post and rest don’t work

I think its not dealing with multiple post id

Here is the full code

Setting a cookie, calling Ajax action with jQuery

  <script type="text/javascript">
/* <![CDATA[ */ 
(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=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

$("#vote").not(".disabled").click(function() {
    var el = $(this);
    el.html('<span id="loader"></span>');
    var nonce = $("input#voting_nonce").val();
    var data = {
        action: 'add_votes_options',
        nonce: nonce,
        postid: '<?php echo $post->ID; ?>',
        ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'            
    };
    $.post('<?php echo admin_url('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.");
            }
            var cookie = getCookie("better_votes");
            if(!cookie) {
                var newcookie = "<?php echo $post->ID; ?>";
            } else {
                var newcookie = cookie + ",<?php echo $post->ID; ?>";
            }
            setCookie("better_votes", newcookie, 365);
        } else {
            alert("There was a problem registering your vote. Please try again later.");
        }
    });
    return false;
}); 
})(jQuery);
/* ]]> */
</script>

This is what I put in my functions.php to register actions

 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 call my vote button and 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'); ?>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T16:05:20+00:00Added an answer on June 16, 2026 at 4:05 pm

    As for a beginning, you shouldn’t have the same id for your button over and over again, so change this:

    <a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
    

    To this:

    <?php 
    if(in_array($post->ID, $hasvoted)) {
        $vtext = "VOTED";
        $class = ' disabled';
    } else {
        $vtext = "VOTE";
        $class = "";
    }
    <a href="javascript:void(0)" id="vote-<?php echo $post->ID; ?>" class="vote-btn<?php echo $class; ?>"><?php echo $vtext; ?></a>
    

    This will result in id attribute of each vote button in the form of “vote-{post id}”. And since I guess you still want to address all of your buttons in some way, you can now use the .vote-btn selector.

    The problem with your JavaScript is that you pass the ID of the post to the script directly. This is fine, when you have only one post on the page, but when you have multiple posts, you have to either print your code multiple times, or get the post ID dynamically.

    I prefer the second option, here’s how your JS code should change in order to get that working:

    <script type="text/javascript">
    /* <![CDATA[ */ 
    (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=/";
    }
    
    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    
    $(".vote-btn").not(".disabled").click(function() {
        var el = $(this),
            nonce = $("input#voting_nonce", el.parent()).val(),
            id = el.attr('id').replace(/vote-/, ''); // get the Post ID
    
        el.html('<span id="loader"></span>');
        var data = {
            action: 'add_votes_options',
            nonce: nonce,
            postid: id,
            ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'            
        };
        $.post('<?php echo admin_url('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.");
                }
                var cookie = getCookie("better_votes");
                if(!cookie) {
                    var newcookie = id;
                } else {
                    var newcookie = cookie + "," + id;
                }
                setCookie("better_votes", newcookie, 365);
            } else {
                alert("There was a problem registering your vote. Please try again later.");
            }
        });
        return false;
    }); 
    })(jQuery);
    /* ]]> */
    </script>
    

    So, in the above code, we get the ID of the post that the user is voting from, by replacing “vote-” with an empty string(so only the ID remains). Note also the following line:

    nonce = $("input#voting_nonce", el.parent()).val(),
    

    In this line, I assume that the nonce input as well as the button have the same parent(although you should be able to use the same nonce for all posts). You can also take your nonce one step further, by changing the code that generates it to:

    <?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce-' . $post->ID, 'voting_nonce'); ?>
    

    And change your add_votes_options function to:

    $postid = $_POST['postid'];
    if ( ! wp_verify_nonce( $_POST['nonce'], 'voting_nonce-' . $postid ) )
        return;
    

    This will bind each nonce to the ID of the post, that the nonce is for.

    I think that’s pretty much your problem. Please try my code and tell me if there are problems with it(if it’s a JS error, please add message from the error console in FireBug, or WebKit’s inspector).


    PP: Just saw this:

    Looking for an answer drawing from credible and/or official sources.

    My answer was backed-up by my experience with WordPress and jQuery – and I earn my living by working mainly with WordPress(less jQuery, but I use it relatively often as well). Hope this will be enough 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Im using timestamps with my sql database. I currently am making a voting system,
I am making a website with a voting system, for some background info, this
I am making a voting system. When user click on a link with class
So I am making a voting system, basically a Thumbs Up & Thumbs Down
Making a new site but something is happening to it in IE8. The social
Making a new site but something is happening to it in IE. I've purchased
Making my first steps in RIA Services (VS2010Beta2) and i encountered this problem: created
Hay i need to hand implemeneting a voting system into a model. I've had
I'm making a little voting tool (voting from 1 to 5) and I have
Making my PHP Command line application support Linux and Windows. Currently it has this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.