如何让wp_logout_url与wp_nav_menu一起工作?

问题描述:

I'm new to wp and now trying to create a link for logging out like this:

      if ( is_user_logged_in() ) { 
        wp_nav_menu( array( 'theme_location'  => 'header-menu', 'depth' => 0,'sort_column' => 'menu_order', 'items_wrap' => '<ul id="%1$s" class="nav navbar-nav">%3$s<li><a href="<?php echo esc_url(wp_logout_url( home_url())) ?>">Logout</a></li></ul>' ) );
      }

The other parts of code are from the theme. I only want to add logout but the result shows that it's not found. Anybody knows how to make it work?

You can achieve this using the wp_nav_menu_items hook. Let's have a look at the following piece of code which shows the login/logout link on the header-menu location.

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

function pd_logout_menu_link( $menu_items, $args ) {
   if ($args->theme_location == 'header-menu') {
      if (is_user_logged_in()) {
         $menu_items .= '<li><a href="'. wp_logout_url() .'">'. __("Log Out") .'</a></li>';
      }
   }
   return $menu_items;
}