I was hoping to create a plugin that adds a new post to a Menu on the second sub-items. However I can't ever seems to get the orders correctly it some times work and sometimes doesn't. Last thing I've tried using ARRAY_A, ARRAY_N and OBJECT however everything seems to be random.

Heres my code:

function spencer_menu_auto() {

    $menu_object = wp_get_nav_menu_object('My Menu');

    $postlist = get_posts('orderby=date&sort_order=DESC');
    $posts = array();
    foreach ($postlist as $post) {
        $posts[] += $post->ID;

    $menuitems = wp_get_nav_menu_items($menu_object->term_id, array(
        'order' => 'ASC',
        'orderby' => 'menu_order',
        'post_status' => 'publish',
        'output' => 'OBJECT',
        'output_key' => 'ARRAY_A'

    $title = array();
    $item_id = array();
    $parent_id = array();
    $index = 0;

    foreach ($menuitems as $item) {

        $title[] += $item->title;
        $item_id[] += $item->ID;

        if ($index === 2) {
            if ($item->title !== get_the_title($posts[0])) {

                wp_update_nav_menu_item($menu_object->term_id, 0, array(
                    'menu-item-title' => __(get_the_title($posts[0])),
                    'menu-item-classes' => 'home',
                    'menu-item-url' => get_permalink($posts[0]),
                    'menu-item-status' => 'publish',
                    'menu-item-parent-id' => $item_id[$index - 1],
                    'menu-item-position' => -1


add_action('init', 'spencer_menu_auto'); 
  • 1
    wp_get_nav_menu_items return a flat array. to know on which level is a item, you need to create a multidimensional array in reading $item->menu_item_parent – mmm Jan 23 '18 at 21:44
  • OK, let's go one step back... What exactly are you trying to achieve? What's the problem that you wanted to solve with this code? I'm almost certain there is an easier and nicer way to solve it. – Krzysiek Dróżdż Jan 30 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.