This will create / handle your endpoint and attempt to load your php if the file is readable. Note: you won’t want to refresh the rewrite rules here but it’ll make sure you can test quickly.
if (!class_exists('WPTestPluginEndpoint')):
class WPTestPluginEndpoint
{
const ENDPOINT_QUERY_NAME = '__my_test_plugin';
// WordPress hooks
public function init()
{
add_filter('query_vars', array($this, 'add_query_vars'), 0);
add_action('parse_request', array($this, 'sniff_requests'), 0);
add_action('init', array($this, 'add_endpoint'), 0);
}
// Add public query vars
public function add_query_vars($vars)
{
$vars[] = static::ENDPOINT_QUERY_NAME;
return $vars;
}
// Add API Endpoint
public function add_endpoint()
{
$query_name = self::ENDPOINT_QUERY_NAME;
add_rewrite_rule('^wp-test-plugin/?', "index.php?{$query_name}=1", 'top');
//////////////////////////////////////
//////////////////////////////////////
// don't do this all the time!!!
//////////////////////////////////////
flush_rewrite_rules(false);
//////////////////////////////////////
//////////////////////////////////////
}
// Sniff Requests
public function sniff_requests()
{
global $wp;
if (isset($wp->query_vars[ self::ENDPOINT_QUERY_NAME ])) {
$this->handle_request(); // handle it
exit;
}
}
// Handle Requests
protected function handle_request()
{
$public_display = WP_PLUGIN_DIR . '/wp-test-plugin/public/partials/wp-test-plugin-public-display.php';
if( is_readable( $public_display )) {
require $public_display;
}
else {
wp_die("Can't find Render Page ". $public_display );
}
die(); // nothing to be done
}
}
$wptept = new WPTestPluginEndpoint();
$wptept->init();
endif; // WPTestPluginEndpoint