2016-09-18 189 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 –

相关问题