我用mmm的提示解决了这个问题,并创建了一个简单的自定义REST端点。
WP1(前端,发送数据):
function send_form_data_to_backend($form_values) {
// add secret-key
$form_values[\'secret_key\'] = "abcde123";
$url = \'http://backend.example.com/wp-json/example/v1/save/\';
$response = wp_safe_remote_post( $url, array(
\'method\' => \'POST\',
\'timeout\' => 15,
\'redirection\' => 5,
\'blocking\' => true,
\'headers\' => array(),
\'body\' => $form_values,
\'cookies\' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo \'Response:<pre>\';
print_r( $response );
echo \'</pre>\';
}
}
WP2(后端,接收数据):
add_action( \'rest_api_init\', \'post_request\' );
function post_request() {
register_rest_route( \'example/v1\', \'/save/\', array(
\'methods\' => \'POST\',
\'callback\' => \'rest_function\')
);
}
/*
* REST Function
*/
function rest_function( $data ) {
if ( $data[\'secret_key\'] == "abcde123" ) {
$msg = example_main_form_processing( $data );
return $msg;
} else {
return "Wrong Key.";
}
}