thebatclaudio / wp-rest-api-v2-menus

Adding menus endpoints on WP REST API v2
47 stars 22 forks source link

Add slug support "wp_api_v2_menus_get_menu_data" #8

Closed niniks closed 5 years ago

niniks commented 6 years ago

I needed the slug with the nav items, my solution:

function wp_api_v2_menus_get_menu_data ( $data ) {
    $menu = new stdClass;
    $menu->items = [];
    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $data['id'] ] ) ) {
        $menu = get_term( $locations[ $data['id'] ] );
        $menu->items = wp_get_nav_menu_items($menu->term_id);
        foreach($menu->items as $item){
            $slug = basename( get_permalink($item->object_id) );
            if(str_replace( parse_url( get_home_url(), PHP_URL_SCHEME ) . '://', '', get_home_url() ) != $slug){
                $item->slug = $slug;
            } else {
                $item->slug = '/';
            }
        }
    }
    return $menu;
}
thebatclaudio commented 5 years ago

Added in #10