Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Como mostrar menus diferentes para usuários conectados no WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Deseja exibir menus diferentes para usuários conectados no WordPress?

Por padrão, o WordPress permite que você mostre o mesmo menu de navegação em um local específico do seu tema. Mas e se você quisesse mostrar um menu diferente para os usuários conectados em seu site?

Neste artigo, mostraremos como exibir facilmente diferentes menus para usuários conectados no WordPress.

Showing different navigtion menus to logged in and non-logged in users in WordPress

Por que mostrar menus diferentes para usuários conectados no WordPress?

Alterar diferentes áreas do seu site WordPress com base nos visitantes e na atividade deles faz com que seu site pareça personalizado para cada usuário.

Esse conteúdo personalizado ajuda a melhorar a experiência do usuário no seu site WordPress.

Agora, se você administra um site em que os usuários não precisam se registrar ou fazer login, provavelmente poderá usar os mesmos menus de navegação em todo o site.

No entanto, outros sites podem se beneficiar muito com a exibição de menus personalizados para usuários conectados.

Por exemplo, sites como uma loja on-line, uma comunidade de sites de associação do WordPress ou uma plataforma de aprendizado on-line podem se beneficiar de menus de navegação personalizados.

Um menu de navegação personalizado para usuários conectados ajuda-os a encontrar mais facilmente os itens para os quais se inscreveram.

Por exemplo, um usuário de uma loja on-line pode gerenciar sua conta, ou um membro de uma comunidade paga pode facilmente renovar sua assinatura ou visualizar os cursos on-line que adquiriu.

Por padrão, o WordPress permite que você crie quantos menus de navegação quiser. No entanto, você só pode optar por mostrar um menu em um local específico do seu tema do WordPress.

Dito isso, vamos dar uma olhada em como alterar facilmente esse comportamento e mostrar menus diferentes para usuários conectados no WordPress.

Criação de menus para usuários conectados e não conectados no WordPress

Independentemente do método utilizado, primeiro você precisará criar os dois menus de navegação que deseja exibir para os usuários conectados e desconectados.

Basta ir até a página Appearance ” Menus no painel do WordPress. Se você já tem um menu de navegação que usa em seu site para todos os usuários, esse pode ser o menu padrão.

Main menu

Depois disso, clique no link “criar um novo menu” para criar um novo menu personalizado para os usuários conectados.

Aqui você pode adicionar itens de menu que deseja mostrar aos usuários registrados ou conectados. Por exemplo, talvez você queira adicionar um link de logout ao seu menu.

No lado esquerdo da tela, você pode ver uma lista das páginas do seu site. Basta marcar a caixa ao lado de qualquer página que você queira adicionar ao menu e clicar no botão “Add to Menu”.

Logged in menu

Você também pode arrastar e soltar os itens de menu no lado direito da tela para reorganizá-los.

Mais abaixo na página, você pode escolher um local para exibir o menu. No entanto, não é necessário atribuir um local a esse menu agora. Faremos isso mais adiante neste artigo.

Não se esqueça de clicar no botão “Save Menu” para armazenar suas alterações.

Para obter mais detalhes sobre a criação de menus, dê uma olhada em nosso guia para iniciantes sobre menus de navegação do WordPress.

Método 1. Mostrar menus diferentes para usuários conectados no WordPress usando um plug-in

Esse método é mais fácil e recomendado para todos os usuários do WordPress.

Primeiro, você precisa instalar e ativar o plug-in Conditional Menus. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

Após a ativação, você precisa acessar a página Appearance ” Menus e alternar para a guia “Manage Locations” (Gerenciar locais).

Aqui, você verá a lista de locais de menu disponíveis definidos no seu tema do WordPress e os menus que estão sendo exibidos no momento.

Manage menu locations

Por exemplo, o local do menu principal está mostrando um menu de navegação intitulado “Menu principal”.

Agora, precisamos dizer ao plug-in para mostrar um menu diferente quando uma determinada condição for atendida.

Para fazer isso, clique no link “+ Conditional Menu” e selecione o menu de navegação que deseja mostrar aos usuários conectados no menu suspenso.

Select logged in menu

Em seguida, você precisa clicar no link “+ Conditions”.

Isso abrirá uma janela pop-up na qual você verá várias condições para escolher.

Select logged in user aa the condition

Basta marcar a caixa ao lado da opção “Usuário conectado” e, em seguida, clicar no botão Salvar.

Agora você pode visitar seu site para ver o menu do usuário conectado em ação. Também é possível fazer logout do administrador do WordPress para visualizar o menu de navegação que será mostrado a todos os outros usuários.

Different menu for logged in users

Método 2. Selecionar manualmente o menu de login no WordPress usando o código

Esse método requer que você adicione código ao seu site WordPress. Se você nunca fez isso antes, dê uma olhada no nosso guia sobre como copiar e colar trechos de código no WordPress.

Primeiro, você precisa adicionar o seguinte código ao arquivo functions.php do seu tema ou a um plug-in específico do site.

function my_wp_nav_menu_args( $args = '' ) {
if( is_user_logged_in() ) {
// Logged in menu to display
$args['menu'] = 43;

} else {
// Non-logged-in menu to display
$args['menu'] = 35;
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

Certifique-se de substituir 43 e 35 pelos IDs dos menus de navegação que você criou anteriormente.

Você pode encontrar o ID de um menu de navegação selecionando-o na página Menus. Você verá o número de ID do menu na barra de endereços do navegador.

Find navigation menu ID

Esperamos que este artigo o tenha ajudado a aprender como mostrar facilmente diferentes menus de navegação para usuários conectados no WordPress.

Talvez você também queira consultar nosso guia sobre como obter um domínio de e-mail gratuito ou ver nosso resumo de especialistas sobre os melhores serviços de telefonia comercial para pequenas empresas.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

97 ComentáriosDeixe uma resposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Clara says

    Works great! I have the problem that I have to menus at the top: A headliner menu and the main menu. When I use the Code and the user is logged in bove menus switch to the logged-in menu. How can I adjust the code so that the headliner menu remains the same?

  3. Echo says

    Would be much easier if you could do it for a specific menu item rather than an entire menu. What would someone with 499 menu items have to do?

    • WPBeginner Support says

      We would not recommend that many menu items as that would be far too many for someone to navigate through which would likely cause an SEO issue if your menu links don’t add value for your visitors

      Administrador

  4. Bk Millanzi says

    this is so helpful, but is there a way to display a username and avatar which can act as a container of other profile menu items, as a drop-down menu?

  5. Amarnadh says

    The path you showed is well and good only for just showing custom menus. But what if i want to show my content to a specific logged in user based on his interests. That is in detail, like various deals sites, when we login and save our interests, the next moment we see deals only on that specific topic. Can we make that possible using WordPress plugins.

  6. Sam says

    Hey there, thanks for the great work. I have a question about multiple user roles.

    So I have two main menus, Menu 1 and Menu 2.

    I would like all users (logged in or out) to see the main menu unless they have the userole of “Alt”, in which case Menu 1 is replaced by Menu 2.

    How would I go about doing that?

  7. Curtis says

    @ERICLEE You can create a child theme to prevent that from happening. I just added this code and need to do the same thing.

  8. shahzaib sarwer says

    can it possible to add the menus in the subscriber profile accept than the home page these menu pages not show on the home page, just on the every subscriber profile. if it possible then please guide me, and tell me how use any pluging for this.

  9. shahzaib sarwer says

    can it possible to add the menus in profile of the subscriber in wp site , if it possible so please anyone guide me what i do and how use any pluging of this work.

  10. Yuda says

    How can the same be achieeved on a multi-language members site? For example show different menu for users logged in in english and a different menu for users logged in with german?

  11. Jan-Paul Kleijn says

    First I thought of a plugin. Gotta quit thinking like that.
    Then I saw your post and was sold.
    Thank you for posting this, you helped me very nicely.

  12. Tarron Acuff says

    So, I have 2 menus. One for the public and another that I would like employees to see when they are logged in. The employee menu would replace the main menu only when an employee is logged in.

    Here is what I am currently using in my functions.php file

    // Set the Role as a body class

    function add_role_to_body( $classes ) {

    $user = wp_get_current_user();

    $user_roles = $user->roles;
    foreach( $user_roles as $role ) {
    $classes[] = ‘role-‘ . $role;
    }

    return $classes;

    }

    add_filter( ‘body_class’, ‘add_role_to_body’ );

    ***Here is what I added for CSS***

    /* First hide the menu items for non “employee” user */
    #top-menu li.menu-for-employee {
    display: none;
    }

    /* Show the menu items for the “employee” user */
    .role-employee #top-menu li.menu-for-employee {
    display: initial;
    }

    When I log in as an employee both menus are showing.

    Thanks in advance.

  13. Joe says

    Hi Guys,

    I nice tutorial but i was wondering could you use the same approach to replace a responsive menu at a certain screen size?

    I have two menus but would rather have just one responsive menu at 768 px by replacing the menu with another.

    Thanks

  14. Pet says

    Awesome job with your guides. I am building my first wordpress site and I am finding your site incredibly helpful in guiding me along, thank you.

    I really wanted to show different menus for logged in users (like ‘edit profile’) and for logged out users and that brought me here. The code you shared works alright for me. I now have two menus which are showing up nice. However, the last part of the code, add filter string, I believe, is messing me up a little bit. Now, another menu is showing under the sidebar widget. The ‘logged-in’ menu. I am using sydney theme and I have tried to no avail to remove this unnecessary menu. Any idea on how I can make it not display?

  15. giovanna says

    Hi can you help me please? I have another trouble please? I need to hide one menu to all and allow only the vendors to see what I have to do please? what is the specific code i have to use please?

  16. Asfaha says

    Hi,

    thanks a lot for this solution, I’ve applied and woks perfect and saved me installing one more plugin.

  17. Shafaq says

    this is the code for replacing existing menu to logged user menu by addming location top-menu and with menu loggedin no need else statement with this

    add_filter( ‘wp_nav_menu_args’, function ( $args )
    {
    if( is_user_logged_in() && $args[‘theme_location’] === ‘top-menu’ ) {
    $args[‘menu’] = ‘loggedin’;
    }
    return $args;
    });

  18. Ashraf Ali says

    ———————————————————–
    function my_wp_nav_menu_args( $args = ” ) {

    if( is_user_logged_in() ) {
    $args[‘menu’] = ‘logged-in’;
    } else {
    $args[‘menu’] = ‘logged-out’;
    }
    return $args;
    }
    add_filter( ‘wp_nav_menu_args’, ‘my_wp_nav_menu_args’ );
    ———————————————————–

    Now how do i get it to work with

    —————————————————

    ———————————————————————————————————————-

    Please Advice

    • Kasper says

      You can lock pages to hide them from logged out users. There are several plugins that make this very easy to do. Users Ultra comes to mind.

  19. Zev says

    Everything worked perfectly.

    However, I still have the issue of a repeated primary menu in the secondary navigation menu section which I can’t seem to remove (I don’t have a secondary menu set up).

    • Vince says

      I’m having the exact issue. The change reflects in the secondary menu location out of nowhere and I too don’t have a secondary menu setup. :/ Please advice how to deal with it.

      Thanks in advance.

  20. Chiranjeevi Vinodkumar says

    LISTEN!!!

    Most of us, uses themes.
    So first go to the functions.php of your theme.
    Search with navigation as keyword.

    In case of Shopkeeper theme..

    ==================================================================
    register_nav_menus( array(
    ‘top-bar-navigation’ => __( ‘Top Bar Navigation’, ‘shopkeeper’ ),
    ‘main-navigation’ => __( ‘Main Navigation’, ‘shopkeeper’ ),
    ‘footer-navigation’ => __( ‘Footer Navigation’, ‘shopkeeper’ ),
    ===================================================================

    This is how you look.. so pick the one which is primary, In my case, Its “Top Bar Navigation” hence used “top-bar-navigation”

    I used the following code and worked like a charm!!!

    This is my way of thanking the author.

    Good day !!

  21. Ann Novakowski says

    Here’s what worked for me with WP . I used this to create a specific primary menu for logged-in Buddypress users. It will NOT affect my footer menu OR social media menu for any visitors, so everyone sees the same secondary menus regardless of whether they’re logged in or not. This is based on all of the comments above (HT to Fransiska!).

    Added the following to my Child Theme’s functions.php file:

    // CHANGE MAIN MENU =ONLY= IF MEMBER IS LOGGED IN

    function my_wp_nav_menu_args( $args = ” ) {
    if ($args[‘theme_location’] == ‘primary’) {
    if( is_user_logged_in()) {
    $args[‘menu’] = ‘logged-in’;
    }else{
    $args[‘menu’] = ‘logged-out’;
    }
    }
    return $args;
    }

    add_filter( ‘wp_nav_menu_args’, ‘my_wp_nav_menu_args’ );

  22. Matthias Campbell says

    Hello,
    I added this code (probably wrongly) in my functions.php within my theme in wordpress editor and now I have a constant 500 server error. Even after removing the code.

    Before this i attempted to create a site specific plugin but that didnt work. Could you please tell me if the snippet requires an opening and closing bracket?
    If so how do i do that?
    My host cant help me now and they’re requesting I pay a programmer to help me for 50Eu per hour. Please help me. Its urgent.
    I am still logged into wordpress but what ever I click I get the 500 error with this specific error.
    PHP Parse error: syntax error, unexpected ‘}’ in line 1194.
    This is because I pasted the snippet after all the text in the functions.php file.
    I then removed the snippet to see if that would fix it, via editor and FTP and I still get the error.
    I look forward to hearing your response.
    Kind regards

    • WPBeginner Support says

      It depends on where you are adding the code. If there is a closing PHP tag before it then you need to add a php start tag like <?php

      If this code is the last thing in the functions file then you don’t need to add a closing tag.

      Administrador

  23. Hubert says

    If you have multiple menu locations and want to apply different menus for each location you can use the code bellow:

    function my_wp_nav_menu_args( $args = ” ) {

    // Primary menu location
    if( ‘primary-main’ == $args[‘theme_location’] ) {

    if( is_user_logged_in() ) {
    $args[‘menu’] = ‘Primary-Logged-In’;
    } else {
    $args[‘menu’] = ‘Primary-Logged-Out’;
    }

    return $args;
    }

    // Secondary menu location
    if( ‘secondary-menu’ == $args[‘theme_location’] ) {

    if( is_user_logged_in() ) {
    $args[‘menu’] = ‘Secondary-Logged-In’;
    } else {
    $args[‘menu’] = ‘Secondary-Logged-Out’;
    }

    return $args;

    }

    }
    add_filter( ‘wp_nav_menu_args’, ‘my_wp_nav_menu_args’ );

  24. Leopold says

    This was almost too easy!
    Thanks alot for the simple article.

    In this way I don’t have to install any plugin..

    • Chris says

      Hi Gaurang,
      I’m curious to know why you feel using the plugin is better, than coding the functions.php file? I was told a while ago to watch how many plugins are actually used for a wordpress site, and the code above seems simple enough; minus the having to monitor every time your theme updates….

      Thanks,

  25. Jason Sisson says

    this is awesome tried it. works. but i also would like to redirect by role
    is that simple or much harder

  26. Ryan R. Bayne says

    Thanks. Working with menu functions for the first time.

    Creating the WTG Portal Manager plugin which will allow a portal to be defined very quickly. Every portal having it’s own menu. The plugin make the relationship between portal and menu clearer plus provide other unique options.

  27. veer2412 says

    thnkx for the help.. but what if i want to show different users different posts on my site.. is there any way to do that using coding??

  28. WPBeginner Staff says

    Under Appearance > Menus you need to choose a location for your menu. Seems like there are two areas on your site where you can add menus. So you need to create two different menus and then assign a location to them.

    • Heather Gile says

      what would the revised code for this be, if there was a distinction of ‘Primary’ and ‘Top’?
      $args[‘primary-menu’] = ‘logged-in’;
      $args[‘top-menu’] = ‘logged-in’;

      else

      $args[‘primary-menu’] = ‘logged-out’;
      $args[‘top-menu’] = ‘logged-out’;

      ?

    • Kyle says

      WordPress will not let me put 2 menus in my “top header” location. The code you provided works, but it changed ALL of my menus to the logged in or out, and is not displaying my normal nav menu

  29. b2995 says

    I have a top menu as well as a site menu (under logo). How would I change the code to switch just that top menu. Right now, ALL my menus change.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.