Last active
February 4, 2019 15:36
-
-
Save harrisoncparker/a770ed741df4778dd2d70afc5ee7ff70 to your computer and use it in GitHub Desktop.
Very simple single class for creating custom endpoint in vanilla wordpress. Based on this stackoverflow answer: https://stackoverflow.com/questions/38901536/wordpress-map-custom-url-to-a-function Not intended to be a full solution.
This file contains hidden or 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 | |
/** | |
* Set Up Endpoint | |
*/ | |
WP_Endpoint::add('some-json', 'getSomeJSON'); | |
function getSomeJSON() | |
{ | |
header('Content-Type: application/json'); | |
// some logic | |
echo json_encode([ | |
'some' => 'data', | |
'more' => 'data' | |
]); | |
die; | |
} |
This file contains hidden or 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 | |
/** | |
* @author Harrison Parker | |
* @github https://github.com/harrisoncparker | |
*/ | |
class WP_Endpoint | |
{ | |
private $route; | |
private $callable; | |
/** | |
* WP_Endpoint constructor. | |
* @param $route | |
* @param $callable | |
*/ | |
public function __construct($route, $callable) | |
{ | |
$this->route = $route; | |
$this->callable = $callable; | |
} | |
/** | |
* @return void | |
*/ | |
public static function add($route, $callable) | |
{ | |
$wpEndpoint = new static($route, $callable); | |
$wpEndpoint->addRewrite(); | |
$wpEndpoint->preventWPFromEvaluatingFalse(); | |
$wpEndpoint->handleEndpointHit(); | |
} | |
/** | |
* @return void | |
*/ | |
private function addRewrite() | |
{ | |
add_action('init', function () { | |
add_rewrite_endpoint($this->route, EP_ROOT); | |
}); | |
} | |
/** | |
* @return void | |
*/ | |
private function preventWPFromEvaluatingFalse() | |
{ | |
add_filter( 'request', function($vars=[]){ | |
if(isset ( $vars[$this->route] ) && empty ( $vars[$this->route] )){ | |
$vars[$this->route] = 'default'; | |
} | |
return $vars; | |
}); | |
} | |
/** | |
* @return void | |
*/ | |
private function handleEndpointHit() | |
{ | |
add_action('template_redirect', function () { | |
if (get_query_var($this->route)) { | |
call_user_func($this->callable); | |
}; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment