getting multiple post id wordpress

I am making a voting system for my theme

It is working fine in single.php

Read More

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'); ?>

Related posts

Leave a Reply

1 comment

  1. 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 🙂