Last active
June 16, 2017 22:05
-
-
Save aolin480/94f907dbac0897e6123cdf5d1da02069 to your computer and use it in GitHub Desktop.
Custom Wordpress endpoint permalink to do whatever you like
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action('init', 'add_api_endpoint'); | |
function add_api_endpoint() | |
{ | |
/** | |
* Set up the endpoint URL my-api | |
* argument setup | |
* /my-api/v1/ | |
* |_ _my_api_key / _api_request / | |
* | |
*/ | |
$regex = 'my-api/v1/'; // the beginning of the API request | |
$regex .= '([^\/]*)'; // match[1] = _my_api_key (required) | |
$regex .= '/?'; // may or not be a leading forward slash, example: if current url is http://www.domain.com/my-api/v1/UzGhdsJF3199 or http://www.domain.com/my-api/v1/UzGhdsJF3199/ | |
$regex .= '([^\/]*)?'; // match[2] = _api_request *(optional, but there really should be something to tell the api what to do) | |
$regex .= '/?'; // may or not be a leading forward slash | |
$location = 'index.php?_my_api_key=$matches[1]&_api_request=$matches[2]'; | |
$priority = 'top'; // use 'top' here or WP will send you to the page if 'bottom' is used; | |
add_rewrite_rule($regex, $location, $priority); | |
} | |
add_filter('query_vars', 'safe_query_vars'); | |
/** | |
* Specify safe variables to use with the endpoint. If a variable is not specified, it will not be available to $this->add_api_endpoint() | |
* @param array $vars an array of query vars | |
* @return array an array of query vars | |
*/ | |
function safe_query_vars($vars) | |
{ | |
$vars[] = '_my_api_key'; | |
$vars[] = '_api_request'; | |
return $vars; | |
} | |
add_filter('template_include', 'handle_api_request', 99); | |
/** | |
* Handle the API requests and route where necessary | |
* @return string wp template URL which should always be returned for non-api calls | |
* @example my-api/v1/{YOUR_API_KEY}/{API_REQUEST}/ | |
*/ | |
public static function handle_api_request($template) | |
{ | |
$my_api_key = get_query_var('_my_api_key', null); | |
$api_request = get_query_var('_api_request', null); | |
die($api_request); | |
return $template; // must be returned, always! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment