REST API Link for the Current Item in the Admin Bar
Adds a "REST" link to the front-end admin bar for administrators that opens the JSON for the post, page, term or author being viewed, which speeds up headless and integration work.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $admin_bar ) {
if ( is_admin() || ! current_user_can( 'manage_options' ) ) {
return;
}
$object = get_queried_object();
$route = '';
if ( $object instanceof WP_Post ) {
$route = rest_get_route_for_post( $object );
} elseif ( $object instanceof WP_Term ) {
$route = rest_get_route_for_term( $object );
} elseif ( $object instanceof WP_User ) {
$route = '/wp/v2/users/' . $object->ID;
}
if ( ! $route ) {
return;
}
$admin_bar->add_node( array(
'id' => 'wpide-rest-link',
'title' => 'REST',
'href' => rest_url( ltrim( $route, '/' ) ),
'meta' => array( 'target' => '_blank', 'rel' => 'noopener' ),
) );
}, 999 );
Notes
Only items exposed in the REST API get a link.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.