首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >wordpress/php:创建一个不刷新页面的向上投票按钮

wordpress/php:创建一个不刷新页面的向上投票按钮
EN

Stack Overflow用户
提问于 2014-09-03 05:30:24
回答 1查看 579关注 0票数 1

这里是初级开发人员,使用wordpress作为平台来制作网站。我希望用户能够点击一个向上投票按钮和向上投票不刷新页面的帖子。我想我可能应该使用javascript来突出显示单击后的按钮,以及更改投票数。然而,我很难弄清楚如何在不刷新页面的情况下运行php脚本(更新数据库)。

提前谢谢你,

EN

回答 1

Stack Overflow用户

发布于 2014-09-03 09:15:07

示例upvote php for post将此代码添加到您的函数文件中...

代码语言:javascript
复制
add_action('wp_ajax_upvote', 'upvote');
add_action('wp_ajax_nopriv_upvote', 'upvote');

function upvote() {
   $postid= $_POST['id'];
   $direction = $_POST['direction'];
   $votes= get_post_meta($postid, '_votes', true);

   if($direction='down') {
      $votes--;
   } else {
      $votes++;
   }

   update_post_meta($postid, '_votes', $votes);
   echo $votes;
   exit();
}

与$_POST变量的任何表单提交一样,上面的代码也需要安全性。不要在你的代码中遗漏这些!!

jQuery代码

代码语言:javascript
复制
jQuery(document).ready(function($){
    $('.arrow').click(function(){ //if your upvote has class arrow?
        //you need someway of passing postid to here!
        //if you want up / downvote -- logic needed here, if not remove direction from below!

        $.ajax({
           type: "POST",
           url: "/wp-admin/admin-ajax.php",

           data: {
              action: 'upvote',
              id: id,
              direction: direction //remove if not needed
           },

           success: function (output) { //do something with returned data

              console.log(output);
              jQuery('#postupvote').text(output); //write to correct id - maybe use postid in the id of the vote count on the page e.g. id="vote23" jQuery('#vote'+postid)
        }


        });
    });

})

有关更多信息,请使用google wordpress ajax

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25632741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档