Shared Navigation Menu From the Main Site
Adds a [wpide_network_menu] shortcode that displays a menu from the main site on any site in the network, so one menu can be maintained in one place.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
add_shortcode( 'wpide_network_menu', function ( $atts ) {
$atts = shortcode_atts( array( 'menu' => '', 'class' => 'wpide-network-menu' ), $atts, 'wpide_network_menu' );
if ( '' === $atts['menu'] ) {
return '';
}
$key = 'wpide_net_menu_' . md5( $atts['menu'] . '|' . $atts['class'] );
$html = get_site_transient( $key );
if ( false === $html ) {
switch_to_blog( get_main_site_id() );
$html = wp_nav_menu( array(
'menu' => $atts['menu'],
'container' => 'nav',
'container_class' => sanitize_html_class( $atts['class'] ),
'container_aria_label' => __( 'Network' ),
'fallback_cb' => false,
'echo' => false,
) );
restore_current_blog();
$html = (string) $html;
set_site_transient( $key, $html, HOUR_IN_SECONDS );
$keys = (array) get_site_option( 'wpide_net_menu_keys', array() );
$keys[] = $key;
update_site_option( 'wpide_net_menu_keys', array_unique( $keys ) );
}
return $html;
} );
add_action( 'wp_update_nav_menu', function () {
if ( ! is_main_site() ) {
return;
}
foreach ( (array) get_site_option( 'wpide_net_menu_keys', array() ) as $key ) {
delete_site_transient( $key );
}
delete_site_option( 'wpide_net_menu_keys' );
} );
Notes
Use [wpide_network_menu menu="Main Menu"] with the menu's name, slug or ID on the main site. The HTML is cached for an hour and cleared when a menu on the main site is saved.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.