Tuesday, 7 May 2013

Adding Log in Log out link to menu

We can add the Log in / Log out link to the menu assigned to the particular Theme Location by using wp_nav_menu_items filter.

Just paste the following code in either plugin files or in the functions.php ( theme file ).

add_filter('wp_nav_menu_items', 'custom_add_login_logout_link', 10, 2);

if(!function_exists('custom_add_login_logout_link')){
    function custom_add_login_logout_link($items, $args) {  

 
        $menu_name = 'primary'; /*Here primary specifies the Theme Location in which your menu is assigned*/
            if ( ! is_user_logged_in() )
                $link = '<a href="' . esc_url( wp_login_url() ) . '">Log In</a>';
            else
                $link = '<a href="' . esc_url( wp_logout_url() ) . '">Log Out</a>';
       
        if ( ($menu_name) && ($args->theme_location == $menu_name) )
            $items .= '<li class="menu-item menu-item-type-post_type menu-item-object-page">'. $link .'</li>';
        return $items;
    }
}

No comments:

Post a Comment