我正在尝试使用此函数php更新自定义帖子类型的自定义字段
add_action(\'wp_ajax_updatemeta\', \'toggle_task_status\');
add_action(\'wp_ajax_nopriv_updatemeta\', \'toggle_task_status\');
function toggle_task_status () {
$post_id = $data[\'post_id\'];
return update_post_meta($post_id , \'task_status\', \'open\');
}
javascript
jQuery("form").on("submit", function () {
console.log("hello");
var post_id = jQuery("#post_id").val();
console.log(post_id);
var post_data = {
action: "updatemeta",
data: {
post_id: post_id,
}
};
jQuery.ajax({
type: "POST",
url: "http://cloud-accounting.com/wp-admin/admin-ajax.php",
data: post_data,
dataType: "json",
cache: false,
error: function (jqHXR, textStatus, errorThrown) {
console.error("it is not working "+textStatus, errorThrown);
},
success: function () {
console.log("it is working");
}
})
})
代码给了我成功,但它不起作用,我在请求前后都看到了相同的结果
最合适的回答,由SO网友:MikeeeGeee 整理而成
我认为你实际上没有收到javascript发送的帖子ID。
function toggle_task_status () {
$post_id = $_POST[\'data\'][\'post_id\'];
$update = update_post_meta($post_id , \'task_status\', \'open\');
if($update){
wp_send_json(\'success\');
} else {
wp_send_json(\'fail\');
}
wp_die();
}
然后在javascript中
success: function (response) {
console.log(response); // should be either \'success\' or \'fail\'
}