Skip to content

Instantly share code, notes, and snippets.

@harrisoncparker
Last active February 4, 2019 15:36
Show Gist options
  • Save harrisoncparker/a770ed741df4778dd2d70afc5ee7ff70 to your computer and use it in GitHub Desktop.
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.
<?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;
}
<?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