2016-09-18 188 views
1

我是WordPress插件開發新手。我目前正在嘗試開發一個額外的計算器插件,其API端點爲example.com/calc/add。我如何在我的WordPress安裝中添加一個新的URL端點,以便插件可以接受'POST'請求(以逗號分隔的列表中的數字)並在添加數字後相應地返回數據?非常感謝!如何創建自定義API端點?

回答

6

可以使用parse_request鉤創建終點,下面是我的插件

// this example creates endpoint like http://emerico.in/api/v2 

add_action('parse_request', 'endpoint', 0); 
add_action('init', 'add_endpoint'); 

/** 
* @param null 
* @return null 
* @description Create a independent endpoint 
*/ 
function endpoint() 
{ 
    global $wp; 

    $endpoint_vars = $wp->query_vars; 

    // if endpoint 
    if ($wp->request == 'api/v2') { 

     // Your own function to process end pint 
     $this->processEndPoint($_REQUEST); 

     // After all redirect to home page 
     wp_redirect(home_url()); 
     exit; 
    } elseif (isset($endpoint_vars['tracking']) && !empty($endpoint_vars['tracking'])) { 
     $request = [ 
      'tracking_id' => $endpoint_vars['tracking'] 
     ]; 

     $this->processEndPoint($request); 
    } elseif (isset($_GET['utm_source']) && !empty($_GET['utm_source'])){ 
     $this->processGoogleTracking($_GET); 
    } 
} 

/** 
* @param null 
* @return null 
* @description Create a permalink endpoint for projects tracking 
*/ 
function add_endpoint() 
{ 

    add_rewrite_endpoint('tracking', EP_PERMALINK | EP_PAGES, true); 

} 
+0

的一個例子我可以作爲什麼'add_rewrite_endpoint(「跟蹤」,EP_PERMALINK | EP_PAGES,真);'呢? – EndenDragon

+0

我正在使用它來添加跟蹤var到查詢..但是你可以從這裏獲得更多關於它的信息https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint –

相關問題