Duplicate WordPress Menus Across a Network of Sites

We recently had to duplicate WordPress menus across a network of sites, and found the available documentation on the matter lacking. In the spirit of bettering the WordPress community, I present the following code snippet.

The code snippet could be included in a plugin (that’s where we used it, to be triggered from the Dashboard), or as a use-once line in the functions.php file in your theme. It relies on being passed an array of ID’s that represent sites in your network.

global $wpdb;
//$blog_list is an array of ID's of sites on the network
foreach ($blog_list AS $blog_id)
{
  switch_to_blog($blog_id);
  wp_delete_nav_menu('YourNavName');//save some hassle, delete the menu if it already exists
  $navID = wp_create_nav_menu('YourNavName');
  $myPage = get_page_by_title('Page Title');//find a page to include in new menu
  if($myPage != null)//if we were successful in getting the page
  {
    $itemData =  array(
      'menu-item-object-id' => $myPage->ID,
      'menu-item-object' => 'page',
      'menu-item-type' => 'post_type',
      'menu-item-status' => 'publish'
    );
    wp_update_nav_menu_item($navID,0,$itemData);
  }
  //following section assigns your new menu to a theme location, so that it can show up on your site
  $locations = get_theme_mod('nav_menu_locations');
  $locations['nav_name'] = $navID;//where nav_name is the name of your menu
  set_theme_mod('nav_menu_locations', $locations);
}

Questions?

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>