+ $menu_item_db_id = wp_update_nav_menu_item( $nav_menu_selected_id, ( $_POST['menu-item-db-id'][$_key] != $_key ? 0 : $_key ), $args );
+
+ if ( is_wp_error( $menu_item_db_id ) ) {
+ $messages[] = '<div id="message" class="error"><p>' . $menu_item_db_id->get_error_message() . '</p></div>';
+ } else {
+ unset( $menu_items[ $menu_item_db_id ] );
+ }
+ }
+ }
+
+ // Remove menu items from the menu that weren't in $_POST
+ if ( ! empty( $menu_items ) ) {
+ foreach ( array_keys( $menu_items ) as $menu_item_id ) {
+ if ( is_nav_menu_item( $menu_item_id ) ) {
+ wp_delete_post( $menu_item_id );
+ }
+ }
+ }
+
+ // Store 'auto-add' pages.
+ $auto_add = ! empty( $_POST['auto-add-pages'] );
+ $nav_menu_option = (array) get_option( 'nav_menu_options' );
+ if ( ! isset( $nav_menu_option['auto_add'] ) )
+ $nav_menu_option['auto_add'] = array();
+ if ( $auto_add ) {
+ if ( ! in_array( $nav_menu_selected_id, $nav_menu_option['auto_add'] ) )
+ $nav_menu_option['auto_add'][] = $nav_menu_selected_id;
+ } else {
+ if ( false !== ( $key = array_search( $nav_menu_selected_id, $nav_menu_option['auto_add'] ) ) )
+ unset( $nav_menu_option['auto_add'][$key] );
+ }
+ // Remove nonexistent/deleted menus
+ $nav_menu_option['auto_add'] = array_intersect( $nav_menu_option['auto_add'], wp_get_nav_menus( array( 'fields' => 'ids' ) ) );
+ update_option( 'nav_menu_options', $nav_menu_option );
+
+ wp_defer_term_counting( false );
+
+ /** This action is documented in wp-includes/nav-menu.php */
+ do_action( 'wp_update_nav_menu', $nav_menu_selected_id );
+
+ $messages[] = '<div id="message" class="updated notice is-dismissible"><p>' . sprintf( __( '<strong>%1$s</strong> has been updated.' ), $nav_menu_selected_title ) . '</p></div>';
+ unset( $menu_items, $unsorted_menu_items );
+
+ return $messages;
+}