unfulvio / wp-api-menus

:abcd: Menu routes for WordPress JSON REST API.
https://wordpress.org/plugins/wp-api-menus
GNU General Public License v2.0
140 stars 59 forks source link

Can you provide a small example on how to use the hook for menu item #35

Open Metin-Ljapo opened 8 years ago

Metin-Ljapo commented 8 years ago

I tried to use the mentioned hook but didnt have any success an example would be nice thanks

sarahannnicholson commented 5 years ago

Hey @Metin-Ljapo,

Here's how I used the hooks in V2. In my custom WordPress plugin, I added this code

// Add ACF Image Field to Menu Item endpoint    (eg /wp-api-menus/v2/menus/:id items[])
add_filter('rest_menus_format_menu_item', 'add_acf_to_menu_item', 100, 1);
if (!function_exists('add_acf_to_menu_item')) {
    function add_acf_to_menu_item($item) {
        $acf_field = get_field( 'Image_Field',  $item['id'] );

        $item['acf'] = $acf_field;
        return $item;
    }
}

// Add Locale to Menu endpoint      (eg /wp-api-menus/v2/menus/:id )
add_filter('rest_menus_format_menu', 'add_locale_to_menu', 100, 1);
if (!function_exists('add_locale_to_menu')) {
    function add_locale_to_menu($rest_menu) {
        $args = array('element_id' => $rest_menu['ID'], 'element_type' => 'nav_menu' );
        $rest_menu['locale'] = apply_filters( 'wpml_element_language_code', null, $args );
        return $rest_menu;
    }
}

There's a 3rd hook in V2, which is rest_menus_format_menus to alter the list of menu items returned (e.g from wp-json/wp-api-menus/v2/menus/)