Skip to content

Instantly share code, notes, and snippets.

@moon0326
Last active May 23, 2022 02:22
Show Gist options
  • Save moon0326/84e0c6f5b3b58bf5b2da16cb3e8f1691 to your computer and use it in GitHub Desktop.
Save moon0326/84e0c6f5b3b58bf5b2da16cb3e8f1691 to your computer and use it in GitHub Desktop.
Find WP Rest Route Callback by an URL
<?php
/**
* Plugin Name: REST Routes CLI
* Version: 0.0.1
*/
defined( 'ABSPATH' ) || exit;
function routes_match( $args ) {
$routes = rest_get_server()->get_routes();
if ( ! isset( $args[0] ) ) {
echo "Missing required argument: path\n";
echo "Example: wp find-rest-route :path\n";
exit;
}
if ( false === strpos( $args[0], 'wp-json') ) {
echo "Invalid REST API endpoint. A valid endpoint must contain 'wp-json'\n";
exit;
}
$path = parse_url( $args[0] )[ 'path' ];
$path = str_replace( '/wp-json', '', $path );
// Remove escape char
$path = trim( $path, "\\" );
foreach ( $routes as $route => $handlers ) {
$match = preg_match( '@^' . $route . '$@i', $path );
if ( ! $match ) {
continue;
}
$methods = [];
foreach ( $handlers as $handler ) {
if ( is_object( $handler['callback'][0] ) ) {
$callback = get_class( $handler['callback'][0] ). '::' .$handler['callback'][1];
} else {
$callback = $handler['callback'][0];
}
$methods[ implode( ',', array_keys( $handler['methods'] ) ) ] = $callback;
}
print_r($methods);
}
}
add_action( 'plugins_loaded', function() {
if ( class_exists( 'WP_CLI' ) ) {
WP_CLI::add_command( 'routes match', 'routes_match' );
}
}, 999 );
@moon0326
Copy link
Author

moon0326 commented May 20, 2022

  1. Install WP CLI
  2. Download this gist and save it in your wp-content/plugins directory.
  3. Activate the plugin
  4. Go to your local directory and run wp help and confirm find-rest-route is listed under SUBCOMMANDS
  5. Run wp find-rest-route :rest-api-endpoint-url

Example

Endpoint: http://woodev.local/wp-json/wc-admin/onboarding/tasks?_locale=user

Usage: wp find-rest-route http://woodev.local/wp-json/wc-admin/onboarding/tasks?_locale=user

OUTPUT

Array
(
    [GET] => Automattic\WooCommerce\Admin\API\OnboardingTasks::get_tasks
    [POST] => Automattic\WooCommerce\Admin\API\OnboardingTasks::get_tasks
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment