Function to add an item to wordpress menu with sorting (display) order

I have been struggeling with wordpres menu for a few days now.

I cant find any good information on the internet that i can understand.
I use the menu that wordpress have. And i want to add new items to it text and also some links.
I cant use wordpress admin GUI for this as the links and text comes from MYSQL calls.

Read More

So far i can get it to display in my menu but my problem is its alwas ends upp in the end of the menu.

Is there a way to make the menu sorted?
From what i understand the function adds the item to the menu and thats why it ends up at the end.
So i have to break down the hole menu and then make the menu but question is how.

Here is my code this adds a “Login” Or “Logout” link in my menu at the end. How do i move it so it will be first in the menu order?

//Add login/logout link to naviagation menu

function add_login_out_item_to_menu( $items, $args ){

    //change theme location with your them location name
    if( is_admin() ||  $args->theme_location != 'main-menu' )
        return $items; 

    $redirect = ( is_home() ) ? false : get_permalink();
    if( is_user_logged_in( ) )
        $link = '<a href="' . wp_logout_url( $redirect ) . '" title="' .  __( 'Logout' ) .'">' . __( 'Logout' ) . '</a>';
    else  $link = '<a href="' . wp_login_url( $redirect  ) . '" title="' .  __( 'Login' ) .'">' . __( 'Login' ) . '</a>';

    return $items.= '<li id="1log-in-out-link" class="menu-item menu-type-link">'. $link . '</li>';
}
add_filter( 'wp_nav_menu_items', 'add_login_out_item_to_menu', 52, 2 );

Related posts

Leave a Reply

1 comment

  1. If you just want to add the item at first then use

    return $items = '<li id="1log-in-out-link" class="menu-item menu-type-link">'. $link . '</li>' . $items;
    

    Just concatenate the $items at the end wit new menu item, this should bring the new item at first.