获取多个post id wordpress


getting multiple post id wordpress

我正在为我的主题制作一个投票系统

在single.php

中运行良好

但是当我把它保存在index.php它只考虑id的第一个帖子和休息不工作

我认为它不能处理多个post id

这是完整的代码

设置cookie,使用jQuery调用Ajax动作

  <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>

这是我在functions。php中用来注册动作的代码

 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);
 }           

这是我如何调用我的投票按钮和计数按钮

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

作为开始,你不应该一次又一次地为你的按钮使用相同的id,所以改变这个:

<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>

这将导致每个投票按钮的id属性以"vote-{post id}"的形式出现。因为我猜你仍然想以某种方式处理你所有的按钮,你现在可以使用.vote-btn选择器。

JavaScript的问题是您直接将帖子的ID传递给脚本。当页面上只有一个帖子时,这很好,但是当您有多个帖子时,您必须多次打印代码,或者动态获取帖子ID。

我更喜欢第二个选项,这是你的JS代码应该如何改变,以使其工作:

<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>

因此,在上面的代码中,我们通过将"vote-"替换为空字符串(因此只保留ID)来获得用户投票的帖子的ID。还要注意下面这行:

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

在这一行中,我假设nonce输入和按钮具有相同的父元素(尽管您应该能够对所有帖子使用相同的nonce)。您还可以进一步使用nonce,将生成它的代码更改为:

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

并将add_votes_options功能更改为:

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

这将把每个nonce绑定到该nonce所针对的文章的ID。

我想那就是你的问题。请尝试我的代码并告诉我是否有问题(如果是JS错误,请在FireBug或WebKit的检查器中添加错误控制台的消息)。


PP: Just saw this:

从可信和/或官方来源寻找答案。

我的回答得到了我使用WordPress和jQuery的经验的支持——我的主要工作是使用WordPress(较少使用jQuery,但我也经常使用它)。希望这就足够了:)