javascript - WordPress/PHP : create an upvote button that does not refresh page

标签 javascript php html wordpress

这里是新手开发人员,使用 wordpress 作为平台制作一个网站。我希望用户能够单击“赞成”按钮并在不刷新页面的情况下对帖子进行赞成。我想我应该使用 JavaScript 来突出显示单击后的按钮并更改投票数。但是,我无法弄清楚如何在不刷新页面的情况下运行 php 脚本(以更新数据库)。

提前致谢,

最佳答案

帖子的示例upvote php将其添加到您的函数文件中......

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

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


        });
    });

})

谷歌 wordpress ajax 了解更多信息

关于javascript - WordPress/PHP : create an upvote button that does not refresh page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25632741/

相关文章:

jquery - CSS 自定义 JQuery ui 对话框

javascript - 仅在可见时加载图像?

javascript - 如何使用 Three.js 从 MySql 数据库加载纹理?

php - mysqli:它可以在一条语句中准备多个查询吗?

php - Magento 管理员编辑表单字段 - 自定义模型字段

php - 按颜色对图像排序

javascript - QScriptEngine中如何定义 `window`对象

javascript - 展平一个 javascript 对象以作为查询字符串传递

javascript - 使用 Javascript 创建新的 div 和选择框

java - 在 ScrollPanel 内时将 FlowPanel 高度设置为 100%?