I am new to WordPress plugin development. I currently am trying to develop an addition calculator plugin which has the API endpoint at example.com/calc/add. How would I add a new URL endpoint to my WordPress installation so the plugin can take in 'POST' requests (numbers in a comma-separated list) and return the data accordingly after adding the numbers? Thank you so much!
You can use parse_request hook for creating end point, below is the example from one of my plugin
// 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);
}
-
May i as what
add_rewrite_endpoint('tracking', EP_PERMALINK | EP_PAGES, true);
does? – EndenDragon Sep 19 '16 at 16:01 -
I am using this for adding tracking var to query .. however you can get more information about it from here codex.wordpress.org/Rewrite_API/add_rewrite_endpoint – Udit Rawat Sep 19 '16 at 16:39
Minimal code
This creates the custom-endpoint
like so http://example.com/custom-endpoint
.
add_action('parse_request', 'register_endpoint', 0);
function register_endpoint() {
global $wp;
if ($wp->request == 'custom-endpoint') {
echo 'hello world'; // process anything here
exit;
}
}