| 176 | |
| 177 | /** |
| 178 | * Import menus from source site to current site. |
| 179 | * |
| 180 | * @param int $source_site_id ID of source site. |
| 181 | */ |
| 182 | protected function import_menus( $source_site_id ) { |
| 183 | switch_to_blog( $source_site_id ); |
| 184 | |
| 185 | // Get all menus from source site. |
| 186 | $menus = wp_get_nav_menus(); |
| 187 | |
| 188 | if ( empty( $menus ) || is_wp_error( $menus ) ) { |
| 189 | restore_current_blog(); |
| 190 | return; |
| 191 | } |
| 192 | |
| 193 | // Get menu locations from source site. |
| 194 | $menu_locations = get_nav_menu_locations(); |
| 195 | |
| 196 | restore_current_blog(); |
| 197 | |
| 198 | $this->create_menus( $menus, $menu_locations ); |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Create menus and add default menu item. |
| 203 | * Also set menu locations as per source site. |
| 204 | * |
| 205 | * @param array $menus All menus of source site. |
| 206 | * @param array $menu_locations Menu locations of source site. |
| 207 | */ |
| 208 | protected function create_menus( $menus, $menu_locations ) { |
| 209 | $ref = array(); |
| 210 | |
| 211 | // Create menu and add one menu item to that menu. |
| 212 | foreach ( $menus as $menu ) { |
| 213 | $new_menu_id = wp_create_nav_menu( $menu->name ); |
| 214 | |
| 215 | if ( is_wp_error( $new_menu_id ) ) { |
| 216 | continue; |
| 217 | } |
| 218 | |
| 219 | // save new menu id reference for old menu id. Use to set menu location. |
| 220 | $ref[ $menu->term_id ] = $new_menu_id; |
| 221 | |
| 222 | $args = array( |
| 223 | 'menu-item-position' => 1, |
| 224 | 'menu-item-type' => 'custom', |
| 225 | 'menu-item-title' => __( 'Home', 'wordcamporg' ), |
| 226 | 'menu-item-attr-title' => __( 'Home', 'wordcamporg' ), |
| 227 | 'menu-item-url' => home_url( '/' ), |
| 228 | 'menu-item-status' => 'publish', |
| 229 | ); |
| 230 | |
| 231 | wp_update_nav_menu_item( $new_menu_id, 0, $args ); |
| 232 | } |
| 233 | |
| 234 | // Set menu to same menu location as source site. |
| 235 | if ( ! empty( $menu_locations ) ) { |
| 236 | foreach ( $menu_locations as $menu_location => $menu_id ) { |
| 237 | $menu_locations[ $menu_location ] = $ref[ $menu_id ]; |
| 238 | } |
| 239 | set_theme_mod( 'nav_menu_locations', array_map( 'absint', $menu_locations ) ); |
| 240 | } |
| 241 | } |