Skip to content

Instantly share code, notes, and snippets.

@terence1990
Last active January 22, 2021 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terence1990/64ac107521142f2e65d8bf9053f7934f to your computer and use it in GitHub Desktop.
Save terence1990/64ac107521142f2e65d8bf9053f7934f to your computer and use it in GitHub Desktop.
Add Menu endpoint in wp-kit/rest-kit, if you don't want to use plugins/wp-rest-api-v2-menus
<?php
#resources/controllers/ApiController.php
public static function getMenu($request) {
$menu = [];
foreach(get_nav_menu_items_by_location($request->get_param('menu')) as $item) {
$item->path = parse_url($item->url, PHP_URL_PATH);
array_push($menu, $item);
}
return $menu;
}
<?php
#resources/functions/menu-functions.php
function get_nav_menu_items_by_location( $location, $args = [] ) {
// Get all locations
$locations = get_nav_menu_locations();
// Get object id by location
$object = wp_get_nav_menu_object( $locations[$location] );
// Get menu items by menu name
$menu_items = wp_get_nav_menu_items( $object->name, $args );
// Return menu post objects
return $menu_items;
}
<?php
#resources/routes.php
rest_route( 'wp/v2', '/menu', [Theme\Controllers\ApiController::class, 'getMenu'] );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment