我正在尝试为我的 Wordpress 博客创建一个投票系统,但我编写的代码不会更新为投票创建的元数据字段,每次我调用该函数来添加投票时,我都会得到值 1返回,
这是我编写的代码:
首先,在帖子的 html 部分中,我创建了一个通过 javascript 调用 loadurl() 的链接:
<a onclick="loadurl()" class='voteup' title="به این پست یه امتیاز"><i class="icon-angle-up"></i></a>
loadurl()调用的脚本如下,它使用ajax从functions.php调用call_me()函数文件
function loadurl() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var value = $.ajax({
type: "POST",
url: ajaxurl,
data:{
//the call_me function for adding a vote in the functions.php
action: 'call_me'
}
})
.fail(function(r,status,jqXHR) {
console.log('failed');
})
.done(function(r,status,jqXHR) {
console.log('success');
//r is the return value of the function call_me();
console.log(r);
});
}
最后在functions.php文件中,我添加了一个 Action 钩子(Hook)(我不太确定)和应该获得当前投票的函数体,并在添加1后将当前投票更新为新的投票计数:
<?php
add_action('wp_ajax_noPriv_call_me', 'call_me');
add_action('wp_ajax_call_me', 'call_me');
add_action('save_post', 'call_me');
function call_me() {
global $wpdb;
$currentvotes = get_post_meta($_POST['post'], 'votes', true);
$currentvotes = $currentvotes + 1;
update_post_meta($_POST['post'], 'votes', $currentvotes);
echo $currentvotes;
die();
}
?>
但是loadurl()函数中console.log(r)函数输出的currentvotes值始终为1,
最佳答案
问题是我没有将 PostID 传递给 callme() 函数,并且由于某种原因,一旦我进入functions.php中的 php 函数,就无法获取 postID 。 所以我添加了 id 变量来存储 postID:
var id= <?php the_ID();?>;
然后通过将以下内容添加到 ajax 调用将其传递给 callme() 函数:
'id': id,
现在 ajax 调用看起来像这样:
function loadurl() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var id= <?php the_ID();?>;
var value = $.ajax({
type: "POST",
url: ajaxurl,
data:{
'id': id,
action: 'call_me'
}
})
.fail(function(r,status,jqXHR) {
console.log('failed');
})
.done(function(r,status,jqXHR) {
/*console.log('success');*/
console.log(r);
});
}
现在使用 $id= $_REQUEST['id'];
我可以检索进行 Ajax 调用的 postID,并且通过以下函数我可以从相应的元数据中读取投票值存储帖子并将其返回给 ajax 调用:
<?php
add_action('wp_ajax_nopriv_call_me', 'call_me');
add_action('wp_ajax_call_me', 'call_me');
function call_me(){
$id= $_REQUEST['id'];
$currentvotes = get_post_meta($id, 'votes', true);
$currentvotes = $currentvotes + 1;
update_post_meta($id, 'votes', $currentvotes);
echo $currentvotes ;
die();
}
?>
关于php - 带ajax调用和php功能的Wordpress投票系统无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18758031/