marketing-raiseup

wordpress 正規API寫法教學

官方教學請參考:點我

非外掛情況:加入在function.php
外掛情況:加入在class的__construct()內

[php]add_action('rest_api_init', function(){
   register_rest_route( 'apitest/v1', '/apitest01/', array(
                        'methods' => 'POST',
		        'callback' => array($this,'testapi'),
		         )
   );
});
//api網址=網站根目錄網址+wp-json/apitest/v1/apitest01[/php]

測試的function(實際上api做的事情)
要記得這邊有個小坑要注意,若上面的methods設定為post但實際上用get方式,反之亦然,api雖然依舊會執行function但會多回傳一個WP_ERROR的json將其視為路徑不存在

[php]function testapi($data){
                //$data相當於PHP變數$POST
		echo json_encode(array('success'=>'測試成功'));
                //單純回傳測試成功
		exit();
	}[/php]

接下來讓我們建立一支html檔做簡單的測試,內容如下:

[html]<form action="網站根目錄網址+wp-json/apitest/v1/apitest01" method="POST">
	<input type="submit" value="送交"/>
</form>[/html]

點擊按鈕送出後得到以下結果即代表成功!
{“success”:”\u6e2c\u8a66\u6210\u529f”}

Like my work??
Don't forget to support or like, so I know you are with me..

CC BY-NC-ND 2.0

Want to read more ?

Login with one click and join the most diverse creator community.