Next previous link in menu

In some cases you need to know the next and previous url of your current post in a WordPress menu. For example if you want to build a multiple step form or wizard application based on a WordPress menu.

The function below takes the menu name as a parameter and uses the global $post object to get the current post id. It collects the menu items and calculates where the current post is in the menu. Then it returns an array with the previous and next id in the menu.

/**
 * Returns the previous and next menu urls of a post
 *
 * @param string $menu_name the menu title
 * @param string $return previous or next url
 */
function get_menu_neighbor_urls( $menu_name, $return = null ) {
     
    global $post;

    // Get all menu items
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object( $locations[$menu_name] );
    $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
 
    if ( ! isset( $links ) ) $links = null;
    if ( ! isset( $urls ) ) $urls = null;
 
    $i = -1;
    foreach ( $menu_items as $item ) {
         
        $i++;
        $id     = get_post_meta( $item->ID, '_menu_item_object_id', true );
        $link = get_page_link( $id );
 
        $links .= $id . ',';
        $urls  .= $link . ',';
 
        if ( $id == $post-> ) {
            $prev_id = $i - 1;
            $next_id = $i + 1;
        }
    }
 
    $links  = explode( ',', $links );
    $urls   = explode( ',', $urls );
 
    if ( array_key_exists( $next_id, $urls ) ) {
        $next_id = $urls[$next_id];
    } else {
        $next_id = false;
    }
 
    if ( array_key_exists( $prev_id, $urls ) ) {
        $prev_id = $urls[$prev_id];
    } else {
        $prev_id = false;
    }
 
    switch ( $return ) {
        case 'next' :
            return $next_id;
            break;
        case 'previous' :
            return $prev_id;
            break;
    }
     
}
Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals