wp_nav_menu find next, previous links

I need to set up some pagination using wp_nav_menu, so I need to access the previous, current and next items in a menu. Any ideas?

Related posts

Leave a Reply

2 comments

  1. Ok, here’s what I came up with – and it works.

    <?php
    $menu_name = 'main-menu';
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
    $menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
    
    $i=-1;
    foreach ( $menuitems as $item ):
    
        $i++;
    
      $id = get_post_meta( $item->ID, '_menu_item_object_id', true );
      $page = get_page( $id );
      $link = get_page_link( $id );
    
        $linkarray.=$id.",";
        $urlarray.=$link.",";
    
      if ($id==$post->ID){
        $previd=$i-1;
        $nextid=$i+1;
      }
    endforeach;
    
    $linkarray=explode(',',$linkarray);
    $urlarray=explode(',',$urlarray);
    
    $nextid=$urlarray[$nextid];
    if (empty($nextid)){
        $nextid=$urlarray[0];
    }
    $previd=$urlarray[$previd];
    if (empty($previd)){
        $previd=$urlarray[$i];
    }
    ?>
    
    <a href="<?php echo $nextid; ?>">Next Item</a>
    <a href="<?php echo $previd; ?>">Previous Item</a>
    
  2. I adapted the previous answer, to include any post items in a menu (not just pages).
    This code returns the previous and next post IDs.

    <?php
    $current_post_id = $post->ID;
    $menu_name = 'guide-menu-frontpage';
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
    $menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
    $i = 0;
    
    foreach ( $menuitems as $item ){
        $menuitems_id_array[] = $item->object_id;
        if ($item->object_id == $current_post_id){
            $prevMenuPosition = $i - 1;
            $nextMenuPosition = $i + 1;
        }
        $i++;
    }
    
    if($prevMenuPosition < 0){
        $prev_id = false;
    } else {
        $prev_id = $menuitems_id_array[$prevMenuPosition];
    }
    
    if($nextMenuPosition > sizeof($menuitems_id_array) - 1){
        $next_id = false;
    } else {
        $next_id = $menuitems_id_array[$nextMenuPosition];
    }
    ?>