WordPress Rest API – Navigational Menu Items

The WordPress REST API provides access to WordPress data using HTTP endpoints. This makes it easy for developers to interact with sites remotely by sending and receiving JSON objects.

As of WordPress Rest API v2, there are many endpoints available to work with posts, pages, users, categories, media, comments, and other settings. Unfortunately, there is no endpoint to get Menu Items. However, you can create custom endpoints to extend WordPress Rest API.

WP REST API Reference: https://developer.wordpress.org/rest-api/reference/
Adding Custom API Reference: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

Get Navigation Menu in WordPress Rest API

First, you need to register a route using register_rest_route(), which will call our custom function. This function should be called in a callback on rest_api_init to take action when the API has been loaded.

Then, create a function such as custom_wp_menu() to return WordPress Menu Items. Here, you need to pass your menu name, slug or ID in wp_get_nav_menu_items() function to return menu items. You can find Menu details in the WordPress Dashboard. When you edit any Menu, Menu id is also visible in the URL. WordPress endpoint returns false if given Menu is not available.

Adding Menu Items in WordPress REST API via code:

// create custom function to return nav menu
function custom_wp_menu() {
    // Replace your menu name, slug or ID carefully
    return wp_get_nav_menu_items('Main Navigation');
// create new endpoint route
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'menu', array(
        'methods' => 'GET',
        'callback' => 'custom_wp_menu',
    ) );
} );

Menu Route URL:


Key Points:

  • We have used ‘wp/v2’ which is a default WP REST API v2 route base. However, you can change it to anything else.
  • You can also change the ‘menu’ term to any other while register route.
  • You can add some prefix to function names to avoid conflict with other plugins.

Reference: https://wordpress.stackexchange.com/a/341267/28526

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.