这里是新手开发人员,使用 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/