我創建了 2 個 REST API 端點來存盤 CPT 資料及其自定義欄位:
存檔資料:xyz.com/wp-json/wl/v2/businesses
單一業務資料:xyz.com/wp-json/wl/v2/businesses/<ID>
這兩個端點都已注冊權限回呼;
register_rest_route( 'wl/v2', '/businesses', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'wl_businesses_posts',
'permission_callback' => '__return_true'
));
它是一個業務目錄網站,其中存在每個“業務”客戶端的通用儀表板 ( ),此儀表板頁面從上面的單一業務資料xyz.com/dashboardREST API 端點提取該“業務”的資料,并填寫頁面上的輸入欄位。
還有一個可供未登錄訪問者訪問的xyz.com/business1頁面(此頁面也從上述單一業務資料REST API 端點提取資料。
我想要完成的是,除了管理員之外,沒有人應該能夠直接窺探存檔資料或顯示高 JSON 資料的單一業務資料端點,以避免竊取在該站點注冊的所有企業的資訊。但同時,我希望wp_remote_retrieve_body( wp_remote_get( $url ) );代碼可以訪問這些端點,以填充儀表板和單個業務資訊頁面。
我嘗試了這段代碼,但它顯然也阻止了頁面代碼發出的請求,以在頁面中提取和填充資料。
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
}
return $result;
});
我不一定在尋找代碼,只是關于如何解決這個問題的方向。
------------------------------UPDATE----------------------------
:
Like I said, since it is a business directory, even non logged-in users should see the archive pages and single business pages of the CPT. I've learned recently about the 'permission callbacks' in register_rest_route arguments, so how would I pass a custom 'key' argument in the wp_remote_get function and receive and validate it in the permission callback?
uj5u.com熱心網友回復:
好的,我已經設法通過在請求中傳遞一個引數來保護我的端點,并且只有當它在其余端點的權限回呼中匹配時,才會檢索資料:
$userData = wp_remote_retrieve_body( wp_remote_get( $url, array(
'body' => array(
'param' => '1'
),
'sslverify' => false,
) ) );
并且在register_rest_route:
'permission_callback' => function( WP_REST_Request $request ) {
if ( '1' == $request->get_param( 'param' ) ) {
return true;
} else {
return false;
}
}
我很高興我不必為此使用插件:D
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/433815.html
標籤:php wordpress wordpress-rest-api
