得到多个帖子id wordpress

时间:2012-12-22 07:02:29

标签: php jquery wordpress

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

在single.php中工作正常

但是当我将它保存在index.php中时,它只会考虑第一个帖子和其余部分的ID不起作用

我认为它不涉及多个帖子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'); ?>

1 个答案:

答案 0 :(得分:2)

首先,你的按钮不应该一遍又一遍地使用相同的ID,所以改变这个:

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

对此:

<?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)。您还可以通过将生成它的代码更改为:

来更进一步
<?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:刚看到这个:

  

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

我的回答得到了我对WordPress和jQuery的体验的支持 - 我通过主要使用WordPress(更少jQuery,但我也经常使用它)来谋生。希望这足够了:))