我正在尝试创建一个 Wordpress 插件,它将接收一个简单的 AJAX 请求,并且目前只发布它的正文。我的代码是:
文件/wp-content/plugins/prova/prova.php:
<?php
/**
* Plugin Name: My Basics Plugin
* Plugin URI: https://example.com/plugins/the-basics/
* Description: Handle the basics with this plugin.
*/
function risposta_mia_azione() {
$param = $_POST["param"];
echo $param;
wp_die();
}
/**
* Register the "book" custom post type
*/
function pluginprefix_setup_post_type() {
}
add_action( 'init', 'pluginprefix_setup_post_type' );
/**
* Activate the plugin.
*/
function pluginprefix_activate() {
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );
/**
* Deactivation hook.
*/
function pluginprefix_deactivate() {
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );
/**
* Uninstallation hook.
*/
function pluginprefix_uninstall() {
}
register_uninstall_hook( __FILE__, 'pluginprefix_uninstall' );
add_action("wp_ajax_nopriv_mia_azione", "risposta_mia_azione");
?>
我的 Wordpress 安装的根目录是http://123.compute.amazonaws.com/wordpress/
. 现在,如果我在该安装的页面中打开开发工具控制台并粘贴以下 jQuery ajax 调用,我将得到POST http://132.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
:
(function( $ ) {
$.ajax({
url : 'http://123.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php',
data : {"action" : "mia_azione", "param" : "ciao"},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
多年来我没有接触过 Wordpress,而且我对 Wordpress 的底层非常不熟悉,从我在类似问题中读到的内容来看,这通常是请求格式不正确的情况,但我真的看不到我的错误。例如,像这样的调用:
ajaxresponse = await fetch("http://ec2-3-129-17-101.us-east-2.compute.amazonaws.com/wordpress/wp-admin/admin-ajax.php", {
method: 'POST', mode: 'no-cors',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({action: "mia_azione", param: "ciao"})
});
会给我这样的回应:
body: ReadableStream
bodyUsed: true
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "basic"
url: "http://123.compute.amazonaws.com/wordpress/w
有人可以帮助我吗?
编辑:正如响应所指出的,我使用了错误的功能 - 我需要的是:https ://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/