WordPress 是世界上最流行的內容管理系統(CMS)之一,可以幫助大小企業建立和建立各種形式的網站內容。但是,WordPress已經不僅僅支援傳統的部落格內容,這在很大程度上要歸功於WordPress REST API。
WordPress REST API 將 WordPress 和其他外部網路應用程式連線起來。它為更方便的交流提供了便利,並幫助您構建與內容管理系統平臺無縫整合的身臨其境、引人入勝的網路體驗。
該 API 使用端點以 JSON 物件的形式檢索和操作 WordPress 內容。有了這些端點,您就可以遠端建立、讀取、更新和刪除(CRUD)WordPress 內容,而無需登入 WordPress 管理後臺,從而提高了靈活性並擴充套件了 WordPress 核心功能以外的功能。
本指南將探討什麼是 WordPress REST API、它的好處、它如何擴充套件 WordPress 的基本功能,以及如何建立、註冊和訪問自定義端點。
前提條件
要學習本教程,您需要:
瞭解 WordPress REST API
WordPress REST API 是一個功能強大的介面,允許您使用標準 HTTP 方法與 WordPress 網站進行程式設計互動。
它的預設功能包括以結構化的JSON格式訪問和操作各種型別的WordPress資料,如、頁面、評論、使用者和分類法。您還可以遠端對內容執行 CRUD 操作。
不過,WordPress REST API的真正價值在於其通過自定義端點實現的可擴充套件性。您可以建立自定義端點來定製 API 以滿足特定需求,例如整合附加功能、第三方服務或獨特的資料結構。這種靈活性使您能夠在 WordPress 的基礎上構建高度定製、功能豐富的應用程式。
如何規劃自定義 API 端點
規劃自定義端點的結構和目的是高效 API 開發的關鍵。根據您的特定需求量身定製的端點需要仔細考慮,以確保最佳功能。戰略規劃有助於提高可擴充套件性和適應性,使端點面向未來,以適應不斷變化的業務需求。
在實施前規劃自定義應用程式介面端點可提供以下支援:
- 明確端點功能 – 規劃端點可明確端點的具體功能、預期資料型別和用途。
- 一致性和開發效率 – 規劃還能確保端點使用、響應型別和格式的一致性,從而改善與應用程式介面的互動。此外,瞭解應用程式介面的目的有助於正確實施,減少開發時間和出錯風險。
- 可擴充套件性和適應性 – 確定端點的需求有助於未來適應不斷變化的業務需求和要求,而無需完全重新設計。
- 安全性 – 正確的端點規劃有助於確定訪問或運算元據是否需要身份驗證。通過應用程式介面獲取內容有時不需要使用者身份驗證。不過,對於包含敏感資料或未經授權資料的內容,必須定義安全要求並實施授權和訪問控制等措施,以幫助確保資料安全。
接下來的實踐部分將介紹如何建立一個自定義端點,從 WordPress 資料庫網站檢索客戶評價,該端點的地址為 site-domain/wp-json/custom/v2/testimonials
。
傳送請求後,端點會返回一個 JSON 物件,其中包含回撥函式中定義的 WordPress 網站上的推薦資訊。
為端點建立自定義型別
首先,您需要建立自定義型別。
- 從 WordPress 管理面板的 “外觀” 部分導航到 “主題檔案編輯器“。
- 開啟主題的 function.php 檔案並新增以下程式碼:
function create_custom_testimonial_type() {register_post_type('testimonials', array('labels' => array('name' => 'Testimonials','singular_name' => 'Testimonial',),'public' => true,'has_archive' => true,'show_in_rest' => true, // This enables REST API support));}add_action('init', 'create_custom_testimonial_type');function create_custom_testimonial_type() { register_post_type('testimonials', array( 'labels' => array( 'name' => 'Testimonials', 'singular_name' => 'Testimonial', ), 'public' => true, 'has_archive' => true, 'show_in_rest' => true, // This enables REST API support )); } add_action('init', 'create_custom_testimonial_type');
function create_custom_testimonial_type() { register_post_type('testimonials', array( 'labels' => array( 'name' => 'Testimonials', 'singular_name' => 'Testimonial', ), 'public' => true, 'has_archive' => true, 'show_in_rest' => true, // This enables REST API support )); } add_action('init', 'create_custom_testimonial_type');
這段程式碼建立了一個自定義的 “testimonials” 型別,並啟用了 WordPress REST API 支援(
'show_in_rest' => true
)。add_action 鉤子呼叫create_testimonial_type
回撥函式,並在執行過程中啟動它。
您可以根據自己的需要刪除或新增標籤和引數。 - 單擊更新檔案儲存更改。
建立
custom_testimonial
文章型別。
重新整理儀表盤,檢視 WordPress 儀表板中新增的 “Testimonials” 選項。新建立的推薦型別:- 點選 Testimonials > 新增文字,建立包含推薦的新帖。您可以使用 Pullquote 區塊。根據推薦信的展示方式,也可以使用其他區塊。
下面是兩個使用 Pullquote 區塊建立的推薦範例:
新建立的客戶推薦
在 WordPress 中註冊自定義端點
註冊自定義端點可使其通過REST API使用。這需要使用 register_rest_route
函式,在 rest_api_init 鉤子上呼叫該函式,並提供一個在路由被呼叫時將被呼叫的回撥方法。
將以下程式碼貼上到主題的 function.php 檔案中:
add_action( 'rest_api_init', 'register_testimonial_rest_route' ); function register_testimonial_rest_route(){ register_rest_route( 'custom/v2', '/testimonials', array( 'methods' => 'GET', 'callback' => 'get_testimonials', ) ); }
register_rest_route()
包含三個引數:
- 路由名稱空間 (
$route_namespace
) – 這是 URL 段的第一部分,應遵循供應商/版本號模式。供應商代表供應商或主題標籤。名稱空間有助於區分端點,並幫助客戶聯絡有關自定義端點的支援。本教程使用custom/v2
名稱空間。 - 基本 URL(
$route
) – 它緊跟名稱空間,是對映到方法的 URL。您可以為路由註冊多個端點。本教程中使用的是/testimonials
路由,它告訴端點檢索推薦信。 - 端點的選項(
$args
) – 這是一個陣列,包含呼叫路由時使用的 HTTP 方法,以及傳送請求時端點將呼叫的回撥函式。我們將在下一節詳細介紹回撥函式。
最後,請注意您的端點地址。端點的格式是 site-address/wp-json/namespace/route
。因此,在本例中,端點將是 https://www.staging.kidspartysanctuary.co.uk/wp-json/custom/v2/testimonials
。
為端點執行回撥函式
建立自定義型別並註冊自定義端點後,下一步就是編寫回撥函式。每次訪問端點時,都會呼叫該回撥函式。
- 使用下面的程式碼宣告
get_testimonials
回撥函式:function get_testimonials(){}function get_testimonials(){ }function get_testimonials(){ }
- 初始化一個空的推薦陣列,用於儲存檢索到的 WordPress 推薦資料:
$testimonials = array();$testimonials = array();
$testimonials = array();
- 為
WP_Query
呼叫設定一個名為$args
的陣列,其中包含查詢引數。$args = array('post_type' => 'testimonials', //specifies you want to query the custom post type'testimonial','nopaging' => true, // no pagination, but retrieve all testimonials at once),$args = array( 'post_type' => 'testimonials', //specifies you want to query the custom post type 'testimonial', 'nopaging' => true, // no pagination, but retrieve all testimonials at once ),$args = array( 'post_type' => 'testimonials', //specifies you want to query the custom post type 'testimonial', 'nopaging' => true, // no pagination, but retrieve all testimonials at once ),
- 建立一個
WP_Query
類例項,該例項接收$args
陣列,根據指定引數執行查詢,並將 WordPress 查詢結果儲存在$query
變數中。$query = new WP_Query($args)$query = new WP_Query($args)$query = new WP_Query($args)
- 編寫一個條件語句來檢查是否有推薦文章。然後,建立一個
while
迴圈來遍歷,並返回推薦的title
和content
。if ( $query->have_posts() ) {while ( $query->have_posts() ) {$query->the_post();$testimonial_data = array( /*an array that stores the titleand content of every post*/'title' => get_the_title(),'content' => get_the_content(),// Add other fields as needed);$testimonials[] = $testimonial_data;}wp_reset_postdata(); /* restores $postglobal to the current post to avoid any conflicts in subsequent queries*/}return rest_ensure_response( $testimonials ); /*ensures response iscorrectly set as a response object for consistency*/if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $testimonial_data = array( /*an array that stores the title and content of every post*/ 'title' => get_the_title(), 'content' => get_the_content(), // Add other fields as needed ); $testimonials[] = $testimonial_data; } wp_reset_postdata(); /* restores $post global to the current post to avoid any conflicts in subsequent queries*/ } return rest_ensure_response( $testimonials ); /*ensures response is correctly set as a response object for consistency*/if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $testimonial_data = array( /*an array that stores the title and content of every post*/ 'title' => get_the_title(), 'content' => get_the_content(), // Add other fields as needed ); $testimonials[] = $testimonial_data; } wp_reset_postdata(); /* restores $post global to the current post to avoid any conflicts in subsequent queries*/ } return rest_ensure_response( $testimonials ); /*ensures response is correctly set as a response object for consistency*/
下面是完整的程式碼:
function get_testimonials() {$testimonials = array();$args = array('post_type' => 'testimonials','nopaging' => true,);$query = new WP_Query( $args );if ( $query->have_posts() ) {while ( $query->have_posts() ) {$query->the_post();$testimonial_data = array('title' => get_the_title(),'content' => get_the_content(),// Add other fields as needed);$testimonials[] = $testimonial_data;}wp_reset_postdata();}return rest_ensure_response( $testimonials );}function get_testimonials() { $testimonials = array(); $args = array( 'post_type' => 'testimonials', 'nopaging' => true, ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $testimonial_data = array( 'title' => get_the_title(), 'content' => get_the_content(), // Add other fields as needed ); $testimonials[] = $testimonial_data; } wp_reset_postdata(); } return rest_ensure_response( $testimonials ); }function get_testimonials() { $testimonials = array(); $args = array( 'post_type' => 'testimonials', 'nopaging' => true, ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $testimonial_data = array( 'title' => get_the_title(), 'content' => get_the_content(), // Add other fields as needed ); $testimonials[] = $testimonial_data; } wp_reset_postdata(); } return rest_ensure_response( $testimonials ); }
- 使用 Postman 測試您的端點,驗證是否可以訪問資料。
Postman 顯示成功響應。您也可以使用瀏覽器進行測試。在瀏覽器位址列輸入 URLsite-domain/wp-json/custom/v2/testimonials
,訪問端點。訪問端點時瀏覽器顯示的結果。
小結
本教程介紹瞭如何實現 WordPress API 自定義端點。要使使用者能夠訪問 WordPress 資料庫資料並與之互動,您只需註冊實現回撥函式的路由。
評論留言