我的 wordpress 中有一個自定義的休息路線:
add_action( 'rest_api_init', function () {
register_rest_route( 'site', '/test-route', array(
'methods' => 'POST',
'callback' => 'handle_webhook',
) );
} );
一切正常,但我現在正在重構,我想更改以前的代碼:
function handle_webhook( $request ) {
//
// processing
//
return new WP_REST_Response('Done, bro!', 200);
die();
}
進入:
function another_function_1( $request ) {
//
// processing
//
return new WP_REST_Response('Done from 1, bro!', 200);
die();
}
function another_function_2( $request ) {
//
// processing
//
return new WP_REST_Response('Done from 2, bro!', 200);
die();
}
function handle_webhook( $request ) {
if ($something) {
another_function_1( $request );
} else {
another_function_2( $request );
}
return new WP_REST_Response('Done, bro!', 200);
die();
}
所以總的來說,我想將代碼分離到另一個函式。問題是我總是收到來自主函式 ( 'Done, bro!', 200)的回應。
當我將returnto if 陳述句放入時,它會起作用:
if ($something) {
return new WP_REST_Response('works here!', 200);
} else {
return new WP_REST_Response('works also here when $something is !true', 200);
}
但是從另一個函式我可以回傳一個回應。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您需要回傳function ():
function another_function_1( $request ) {
//
// processing
//
return new WP_REST_Response('Done from 1, bro!', 200);
/** die(); */
}
function another_function_2( $request ) {
//
// processing
//
return new WP_REST_Response('Done from 2, bro!', 200);
/** die(); */
}
function handle_webhook( $request ) {
if ($something) {
return another_function_1( $request ); /** Added return */
} else {
return another_function_2( $request ); /** Added return */
}
/** With the if {} else {} above, this code will never be reached.
/** return new WP_REST_Response('Done, bro!', 200); */
/** die(); */
}
否則,它只會在函式呼叫之外繼續前進。
此外,沒有必要die();在回傳后,代碼是靜音的,因為程序永遠不會到達代碼中的那個點。
uj5u.com熱心網友回復:
嘗試類似:
function handle_webhook( $request ) {
if ($something) {
$result = another_function_1( $request );
} else if ($somethingElse) {
$result = another_function_2( $request );
} else {
$result = new WP_REST_Response('Default', 200);
}
return $result;
}
由于 HTTP 和/或 HTTPS 的作業方式是這樣的,您只能發送一個回應(針對一個請求),但您可以使用
JSON陣列或其他東西來解決該限制和 .
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/377584.html
標籤:php WordPress的 wordpress-rest-api
上一篇:基于ACF值的入隊腳本
下一篇:洗掉重復值并覆寫陣列
