Skip to content

Instantly share code, notes, and snippets.

@kjbenk
Last active June 12, 2017 12:13
Show Gist options
  • Save kjbenk/dd03e11ebda625b846978e387e1d3685 to your computer and use it in GitHub Desktop.
Save kjbenk/dd03e11ebda625b846978e387e1d3685 to your computer and use it in GitHub Desktop.
WordPress: Add other menu items to existing menu
<?php
/**
* Adds menu items to existing menu. This supports adding complete menus to existings menus
* as well.
*
* @param array $sorted_menu_items The menu items, sorted by each menu item's menu order.
* @param stdClass $args An object containing wp_nav_menu() arguments.
*/
function add_other_menu_items( $sorted_menu_items, $args ) {
// Do nothing if there is no menu given.
if ( empty( $args->menu ) ) {
return $sorted_menu_items;
}
// Get the current menu's term ID.
if ( $args->menu instanceof WP_Term ) {
$term_id = $args->menu->term_id;
} else {
$term_id = (int) $args->menu;
}
// Get the secondary menu.
$new_menu = (int) $this->get_secondary_menu();
// The existing menu ID to add the items to.
$existing_menu = 'existing-menu';
// Perform checks.
if (
! empty( $term_id )
&& $term_id !== $new_menu // Cannot add the same menu twice.
&& ! empty( $new_menu )
&& ! empty( $args->menu_id )
&& $existing_menu === $args->menu_id
) {
$new_items = wp_get_nav_menu_items( $new_menu, [
'update_post_term_cache' => false,
] );
if ( ! empty( $new_items ) ) {
_wp_menu_item_classes_by_context( $new_items );
// Add the items to the current menu.
array_push( $sorted_menu_items, ...$new_items );
}
}
return $sorted_menu_items;
}
add_filter( 'wp_nav_menu_objects', 'add_other_menu_items', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment