Last active
May 23, 2022 02:22
-
-
Save moon0326/84e0c6f5b3b58bf5b2da16cb3e8f1691 to your computer and use it in GitHub Desktop.
Find WP Rest Route Callback by an URL
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 | |
/** | |
* 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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wp-content/plugins
directory.wp help
and confirmfind-rest-route
is listed underSUBCOMMANDS
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