4

All

I am using wordpress custom menu, and there is one menu as Logout. I know wordpress Logout function <?php echo wp_logout_url(); ?>

But how can i use it in custom menu ?

2 Answers 2

6

Not sure how and where you can create a custom button, but you can add such a link per filter: Add a filter function to 'wp_nav_menu_objects' and insert the link where you need it.

Here is a basic example:

add_filter( 'wp_nav_menu_objects', 'wpse_46547_add_log_out_link', 10, 2 );

function wpse_46547_add_log_out_link( $sorted_menu_items, $args )
{
    $link = array (
        'title'            => 'Log out',
        'menu_item_parent' => 0,
        'ID'               => '',
        'db_id'            => '',
        'url'              => wp_logout_url()
    );

    $sorted_menu_items[] = (object) $link;

    return $sorted_menu_items;
}

You should modify the code:

  • Check if you are on the correct menu. For example require a class has_log_out_link for the menu_class parameter on wp_nav_menu and test $args->menu_class.
  • I18n for the menu title. ;)
  • Set menu_item_parent to a post ID other than 0 if you need the link in a sub menu.
  • There are more parameters for the link, see my other answer to inspect those.
2
  • I have side bar in there, there are custom menu, i have added there pages & category. But last menu is Logout, When user click on logout menu, i want to logout that user.
    – Ajay Patel
    Commented Mar 23, 2012 at 7:19
  • 1
    Yes, I understood this. Create an item, add it to the custom menu, and you are done.
    – fuxia
    Commented Mar 23, 2012 at 7:27
2

In case someone else struggles with this, the easiest way I found was to simply add the Log out menu item exactly where you want it by using the custom link option. Make the url something unique like logouturl and the simply add this code to your functions.php file or wherever you prefer adding custom code.

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

function wp123e_loginout_menu_link( $items, $args ) {
   if ($args->theme_location == 'primary') {
      if (is_user_logged_in()) {
         $items = str_replace('logouturl', wp_logout_url(), $items);
      }
   }
   return $items;
}

Remember to change this first parameter of str_replace to the string used in the custom link of the menu settings. You might also need to change the theme_location from primary to the appropriate location.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.