Last active
March 30, 2025 14:38
-
-
Save KevinBatdorf/938b6a4ffecaf8e996480cf408504a36 to your computer and use it in GitHub Desktop.
A simple router for WordPress REST API - Laravel-like
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 | |
defined( 'ABSPATH' ) or die; | |
namespace Kevin; | |
class Router extends \WP_REST_Controller | |
{ | |
protected static $instance = null; | |
public function getHandler($namespace, $endpoint, $callback) { | |
\register_rest_route( | |
$namespace, | |
$endpoint, | |
[ | |
'methods' => 'GET', | |
'callback' => $callback, | |
'permission_callback' => function() { | |
return \current_user_can('upload_files'); | |
}, | |
] | |
); | |
} | |
public function postHandler($namespace, $endpoint, $callback) { | |
\register_rest_route( | |
$namespace, | |
$endpoint, | |
[ | |
'methods' => 'POST', | |
'callback' => $callback, | |
'permission_callback' => function() { | |
return \current_user_can('upload_files'); | |
}, | |
] | |
); | |
} | |
public static function __callStatic($name, array $arguments) { | |
$name = "{$name}Handler"; | |
if (is_null(self::$instance)) { | |
self::$instance = new static(); | |
} | |
$r = self::$instance; | |
return $r->$name('your-rest-namespace/maybe-version-too', ...$arguments); | |
} | |
} |
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 | |
defined( 'ABSPATH' ) or die; | |
use Kevin\Router; | |
add_action('rest_api_init', function() { | |
Router::post('/login', function($payload) { | |
$KBSDResponse = wp_remote_post( | |
"https://example.com/v1/login", | |
['headers' => []], // Maybe an auth header? | |
); | |
return new WP_REST_Response( | |
json_decode(wp_remote_retrieve_body($KBSDResponse), true), | |
wp_remote_retrieve_response_code($KBSDResponse) | |
); | |
}); | |
Router::get('/all', function($payload) { | |
return new WP_REST_Response(); // etc etc | |
}); | |
// You could also use a class and namespace it | |
Router::get('/the-thing', [MyNamespace\ThingController::class, 'data']); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment