i'm create custom admin page via add_menu_page
, let's imagine that my custom page has url
wp-admin/admin.php?page=settings_page
then i'm checki is_admin()
function via var_dump
on my settings_page
and it returns true
- that's OK, but when i'm wrap rest_api_init
action in if is_admin()
statement, like this:
if(is_admin()){
add_action('rest_api_init', [$this, 'myRegisterRoutesFunction']);
}
it returns me 404 - No route was found matching the URL and request method
. But if i remove if
statement, it works fine. Can't understand why, thanks for the advices!
i'm create custom admin page via add_menu_page
, let's imagine that my custom page has url
wp-admin/admin.php?page=settings_page
then i'm checki is_admin()
function via var_dump
on my settings_page
and it returns true
- that's OK, but when i'm wrap rest_api_init
action in if is_admin()
statement, like this:
if(is_admin()){
add_action('rest_api_init', [$this, 'myRegisterRoutesFunction']);
}
it returns me 404 - No route was found matching the URL and request method
. But if i remove if
statement, it works fine. Can't understand why, thanks for the advices!
2 Answers
Reset to default 6Essentially, you shouldn't wrap your REST route declarations inside is_admin() since Wordpress will not load them (see @DarkNueron comment).
What you can do is pass a 'permission_callback' function to the register_rest_route
function. If the function returns true, the request is allowed to continue; if false, an error is returned.
So you could do:
register_rest_route('your-namespace/v1', '/options/', [
'methods' => 'PATCH',
'callback' => [__CLASS__, 'update_option'],
'permission_callback' => function () {
return current_user_can('manage_options');
}
]);
It's due to the way WP initializes the REST endpoints. It works something like this:
Someone POST
s to an endpoint, f.ex /wp-json/my/custom/endpoint
. Wordpress tries to figure out if there is a route for that endpoint by calling the rest_api_init
hook, and running any custom code that sets up that route.
Now check out the source for is_admin
:
function is_admin() {
if ( isset( $GLOBALS['current_screen'] ) ) {
return $GLOBALS['current_screen']->in_admin();
} elseif ( defined( 'WP_ADMIN' ) ) {
return WP_ADMIN;
}
return false;
}
Nothing magical here, it just checks what screen you're currently on. However, there's no "screen" when a REST call comes in. So is_admin
is always going to return false.
So thats what happens when you wrap your REST initialization logic with is_admin
.