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 desativar a barra de administração do WordPress para todos os usuários, exceto os administradores

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 desativar a barra de administração do WordPress para todos os usuários, exceto os administradores?

Por padrão, é possível desativar facilmente a barra de administração do WordPress para usuários individuais. No entanto, isso pode levar algum tempo se houver muitos usuários registrados no seu site.

Neste artigo, mostraremos como desativar facilmente a barra de administração do WordPress para todos os usuários, exceto os administradores.

How to disable WordPress Admin Bar for All Users except administrators

O que é a barra de administração do WordPress?

Por padrão, o WordPress mostra uma barra de administração na parte superior da tela para todos os usuários conectados. Quando você estiver conectado à sua conta, poderá ver essa barra de ferramentas na área de administração do WordPress e em todas as outras páginas.

The WordPress admin bar

A barra de ferramentas de administração do WordPress tem atalhos úteis para diferentes áreas de back-end do WordPress, e esses atalhos mudam de acordo com a função e as permissões do usuário no WordPress.

No entanto, a barra de administração pode distrair quando você estiver olhando para o front-end do seu site.

Isso também pode afetar o design do seu site e a experiência do usuário. Isso pode ser um problema se você estiver criando ou gerenciando um site WordPress para terceiros, pois isso os impede de ver como o site deles realmente é.

Felizmente, há várias maneiras de desativar a barra de administração para todos os usuários, exceto os administradores. Basta usar os links rápidos abaixo para ir para o método que você deseja usar:

Tutorial em vídeo

Subscribe to WPBeginner

Se você preferir instruções escritas, continue lendo.

Método 1: Desativar a barra de administração do WordPress para usuários individuais

Você pode desativar a barra de administração para usuários específicos simplesmente editando o perfil de usuário deles. Esse é um método rápido e fácil se você só precisa remover a barra para um pequeno número de pessoas. No entanto, se você administra um site de associação com muitos usuários, recomendamos que escolha um método diferente.

Para remover a barra de administração manualmente, basta acessar a página Usuários ” Todos os usuários no painel de administração do WordPress. Em seguida, passe o mouse sobre o usuário que não precisa da barra de administração e clique em “Editar” quando ele aparecer.

How to edit a user's profile in WordPress

Isso abrirá o perfil do usuário.

A partir daí, desmarque a caixa ao lado da opção “Mostrar barra de ferramentas ao visualizar o site”.

How to hide the admin toolbar for non-admin users

Depois disso, role até a parte inferior da tela e clique em “Update User” (Atualizar usuário) para salvar as alterações. Isso desativará a barra de administração somente para essa pessoa específica.

Para ocultar a barra de ferramentas para mais usuários, basta seguir o mesmo processo descrito acima.

Método 2: desativar a barra de administração para todos os usuários, exceto os administradores (recomendado)

Se você precisar ocultar a barra de administração para várias pessoas diferentes, alterar manualmente as configurações de cada usuário exigirá muito tempo e esforço.

Por esse motivo, recomendamos desativar a barra de administração adicionando um código ao arquivo functions.php, que é um arquivo de tema do WordPress. Se você nunca fez isso antes, consulte nosso guia sobre como copiar e colar trechos de código no WordPress.

Alguns guias informam que você deve editar os arquivos do tema manualmente, mas isso pode causar erros comuns do WordPress e até mesmo danificar completamente o seu site.

Por esse motivo, recomendamos o uso do WPCode. Ele é o melhor plugin de snippet de código e facilita a adição de código personalizado no WordPress sem colocar seu site em risco.

Primeiro, você precisará instalar e ativar o plug-in gratuito WPCode. Para obter mais informações, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

Depois que o plug-in for ativado, vá para Code Snippets ” Add Snippet.

Hiding the admin toolbar using WPCode

Aqui, você verá todos os snippets pré-fabricados que pode adicionar ao seu site. Isso inclui um snippet que permite desativar completamente os comentários, fazer upload de tipos de arquivos que o WordPress normalmente não suporta, desativar páginas de anexos e muito mais.

Na próxima tela, passe o mouse sobre a opção “Add Your Custom Code (New Snippet)” e clique no botão “Use snippet” quando ele aparecer.

Adding custom code to your WordPress website with WPCode

Na próxima tela, digite um título para o snippet de código. Isso é apenas para sua referência, portanto, você pode usar o que quiser.

Em seguida, abra a lista suspensa “Code Type” (Tipo de código) e escolha “PHP Snippet”.

Adding a PHP snippet to WordPress using WPCode

Feito isso, basta colar o seguinte código no editor:

add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
  show_admin_bar(false);
}
}

Esse código identifica todos os usuários não administradores que não estão vendo o painel de administração no momento. Para esses usuários, ele desativa a barra de administração do WordPress.

Depois disso, role a página para baixo até a seção “Inserção”. Aqui, você pode manter o método padrão “Auto Insert” para garantir que o código seja executado em todos os lugares.

Automatically inserting code into a WordPress website

Por fim, role até a parte superior da tela e clique no controle deslizante “Inactive” (Inativo) para que ele mostre “Active” (Ativo).

Em seguida, basta clicar no botão “Salvar snippet” ou “Atualizar” para ativar o snippet de código.

Publishing a custom code snippet to WordPress

É isso aí! Lembre-se de verificar seu site WordPress para ter certeza de que tudo está funcionando bem.

Método 3: Desativar a barra de administração do WordPress para todos os usuários, exceto administradores (nenhum código necessário)

Se você não quiser adicionar código ao seu site, poderá ocultar a barra de administração usando um plug-in. O Hide Admin Bar Based on User Roles permite remover a barra de ferramentas com base em diferentes funções de usuário, portanto, é uma boa opção se você quiser desativar a barra para todos os membros, clientes do WooCommerce ou alguma outra função de usuário.

Primeiro, você precisa instalar e ativar o plug-in Hide Admin Bar Based on User Roles. 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 ir para a página Settings ” Hide Admin Bar Settings. A partir daí, marque as caixas ao lado das funções de usuário em que deseja desativar a barra de administração.

Hiding the admin toolbar for specific user roles

Feito isso, basta clicar em “Save Changes” (Salvar alterações) para armazenar suas configurações.

Método 4: desativar a barra de administração para todos os usuários (incluindo administradores)

Deseja desativar a barra de administração para todos os usuários, incluindo os administradores do site?

Você pode fazer isso adicionando um código que desabilita a barra de administração para todos que estão visualizando as páginas públicas do seu site. Isso significa que a barra de administração só aparecerá quando você estiver na área do painel do WordPress.

Para simplificar as coisas, o WPCode tem o trecho de código exato de que você precisa em sua biblioteca de trechos integrada. Basta acessar Code Snippets Library.

The WPCode code snippet plugin for WordPress

Aqui, procure por “Disable The WP Admin Bar” (Desativar a barra de administração do WP).

Quando o snippet correto for exibido, basta clicar no botão “Usar snippet”.

The ready-made Disable The WP Admin Bar code snippet

O plug-in adicionará automaticamente o código ao seu site, dará ao código um título descritivo, escolherá o método de inserção correto e até mesmo adicionará tags para ajudá-lo a identificar o snippet.

Veja a seguir a aparência do código:

/* Disable WordPress Admin Bar for all users */
add_filter( 'show_admin_bar', '__return_false' );

Agora, tudo o que você precisa fazer é alternar a chave de “Inativo” para “Ativo” e, em seguida, clicar em “Atualizar”.

Adding custom code to WordPress

Agora, se você visitar o front-end do seu site enquanto estiver conectado à sua conta do WordPress, a barra de administração desaparecerá.

Esperamos que este artigo o tenha ajudado a aprender como desativar a barra de administração do WordPress para todos os usuários, exceto os administradores. Talvez você também queira ver nosso guia definitivo de segurança do WordPress e nossa comparação dos melhores construtores de páginas do WordPress para criar layouts de página personalizados sem nenhum código.

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

162 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. Moinuddin Waheed says

    This is very needed to hide the admin bar to all the user’s except the administrator.
    I have thought of doing this multiple times over specially when I was running news website and I had many authors and contributors.
    Showing them admin bar is not only unnecessary but annoying too.
    Really appreciate for the steps to get rid of this admin bar and keep it for only the administrator.

  3. Amos Showole says

    Wow… This is great, you solved an issue I faced with on one of my WordPress website that BuddyPress was installed on….

  4. Paul says

    Using the after_setup_theme hook doesn’t always work. Try this instead:

    function remove_admin_bar( $value ) {
    return ( current_user_can( ‘administrator’ ) ) ? $value : false;
    }
    add_filter( ‘show_admin_bar’ , ‘remove_admin_bar’);

  5. Joey says

    What would be the code if I want to add Editor and Admin to show the Admin bar..

    if (!current_user_can(‘administrator’) && !is_admin())…

    if (!current_user_can(‘editor’) && !is_editor())…

    would it be if (!current_user_can(‘administrator’) && !is_admin() || !current_user_can(‘editor’) && !is_editor())

    would this work?

    • WPBeginner Support says

      For what you are wanting, you would want to remove: && !is_editor()

      Then it should work how you are wanting.

      Administrador

  6. Basia says

    Hi,
    I hide admin bar with plugin You recommend, but when subscriber log in he can still click on “view my profile” and see wp dashboard. Can I disable that?

    • WPBeginner Support says

      If method 3 is not working for you, we would recommend trying one of the other methods to test.

      Administrador

    • WPBeginner Support says

      You may want to try clearing your cache for the most common reason for the change not being visible.

      Administrador

  7. Paul says

    What exactly does this disable? I still see an admin bar and I have access to menu options when I go to example.com/wp-admin when i’m logged into a subscriber account.

    • WPBeginner Support says

      You would want to ensure the code was properly added for the most likely cause of the admin bar not being hidden otherwise, you could also have a plugin that would be overriding this code.

      Administrador

  8. Marc Korden says

    Cannot add the admin code in my theme:

    Communication with the site not possible to check for errors, the PHP adjustment has been reversed. The PHP file change needs to be changed in another way, for example using SFTP.

  9. Agha Mubasher says

    Hello there…!
    First of all i simply love the work wpbeginner, as you always bring forward the simplest solutions to our wordpress issues. Your website and Youtube channel has always been helpful for me. Thumbs Up for that.. :)

    I had issue with hiding the admin bar for the subscribers only. Now after applying your code in the function.php it is hidden for my editors also.
    Is there any way that my editors also can see the admin bar and only it should be hidden from the subscribers..!!

    • WPBeginner Support says

      For that, you would need to target another permission that your editor has instead of what we are targeting such as edit_others_posts

      Administrador

  10. Jesaja says

    On my website it says:

    “Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.”

    What to do now?

  11. Jim says

    Can this code be altered to allow the WordPress Admin bar for Admins AND moderators, but hide it for everyone else?

    Thanks!

  12. Andreas says

    If a user knows the URL structure of WordPress he can easily browser to /wp-admin/ and there the admin toolbar will be visible. Also, the easiest way is to deactivate it in the user setting if you have a small number of users.

  13. Adam Pressman says

    Doesn’t work. Well, to be fair, works when you first use it but then something happens and it doesn’t anymore. nothing is overwriting the functions.php and the code is there but usually after the first login, logout cycle a subsequent login will see the admin bar return.

  14. Cesar says

    I have created a social media site using several plugins and everything works fine but for one issue. Pages are successfully restricted and redirected (Buddypress pages, blogs, etc) for non-logged in users.

    However the main issue I am having is that non-logged in users can still have access to blog posts and user profile pages via widgets placed on side bar and footer and I cannot seem to find a solution anywhere.

    Any ideas on the matter, plugins or code that I can insert in the child theme?

    I have been looking for a solution for over a day and all there is there is how to restrict pages and partial content but nothing works on the widget links, they keep going thru the restrictions in place.

    Thanks

    • WPBeginner Support says

      Hey Cesar,

      There are several widgets and plugins that allow you to hide widgets from non-logged in users. However, if non-logged in users know the URL, then they would still be able to access those URLs directly. You need to review your plugin settings and see if you can find the option to hide profile pages from non-logged in users.

      Administrador

  15. Shabz says

    This code or several others that I tried from the comments isn’t working. I’m trying to remove that dumb silver/black wordpress tab above my menu that shows up for all of my website’s users. How do I remove that? Please help :)

    • Jack Hernandez says

      As mentioned in the article, you included a way for users to edit their profiles through the front end without the admin bar. How did you accomplish that.
      Thanks

  16. Chouchouda says

    Hello, some issue , i have done everything but can’t hide toolbar for owner user in frontend , but can do this for admin user , incredible.
    I’m using search& go theme wordpress , Thank for your help.

  17. Alex says

    Hello,

    Code needs a little updating. This is the code I would use to redirect by role.

    /*Hide admin bar for certain roles*/
    function hide_admin_bar() {
    if(is_user_logged_in() ) {
    $current_user = wp_get_current_user();
    if ( in_array( ‘subscriber’, (array) $current_user->roles ) ) {
    add_filter(‘show_admin_bar’, ‘__return_false’);
    }
    }
    }

    Hope this helps.

    • Brandon says

      Thanks for this updated code, Alex. Simple and works great.

      Put it in child theme functions.php and forget about it. :)

    • Yuki Zain says

      Thanks, Alex but I’m editing a bit

      /*Hide admin bar for certain roles*/
      if(is_user_logged_in() ) {
      $current_user = wp_get_current_user();
      if ( in_array( ‘subscriber’, (array) $current_user->roles ) ) {
      add_filter(‘show_admin_bar’, ‘__return_false’);
      }
      }

    • randalf says

      Very nice :) but what do I do if I have two roles as a result of bbpress plugin.. That is registered users have the subscriber role in whole site and participant role in bbpress.
      Please help

  18. Scott says

    Hi,

    I inserted your code to remove the Admin bar from my membership site. Unfortunately it also removed it from me, the Admin (even thought I used your first option above). I am using the Tesseract Pro theme. Do you have any suggestions? Thanks

  19. Inder Singh says

    Dear Sir,
    I have 2 admin user and i want to show admin bar for first user and remove admin bar for second user in wordpress.
    How can i do it.

    Thanks for support.

  20. SG says

    I tried using this and I got that code Parse error: syntax error, unexpected ‘}’ in /home/content/76/10323476/html/wp-content/themes/digitalscience-apex/functions.php on line 168 and I can’t get my site back even after deleting it.

  21. Krzysiek Dróżdż says

    Well, I wouldn’t use current_user_can for that… Codex says, that you can use it for role checking, but in the code you can find:

    * While checking against particular roles in place of a capability is supported
    * in part, this practice is discouraged as it may produce unreliable results.

    So… Much better and secure way to do this is:

    $user = wp_get_current_user();
    if ( ! in_array( ‘administrator’, (array) $user->roles ) ) {

    }

  22. Lyndal Sirit says

    i used it and it crashed my site, trying desperately to fix it now, i took the code back out and updated but I am getting an Error: Parse error: syntax error, unexpected ‘3’ (T_LNUMBER) in /home/lyndalspirit/public_html/wp-content/themes/primer/functions.php on line 516

    • WPBeginner Support says

      Hi Lyndal,

      Some times when users copy code from websites like WPBeginner, they also copy the line numbers which they are not supposed to copy. When they paste this code in their functions.php file it causes an error.

      You need to connect to your site using an FTP client. Locate your functions.php go to the code you added and remove it. Save your changes.

      Administrador

  23. Chris says

    This worked fine for me as-is, i stripped out the line numbers and stuck it at the end of my theme functions.php – instant success. thanks so much.

    • WPBeginner Support says

      Login to your WordPress admin area using an Administrator account. Click on the Users menu item from the admin sidebar. This will show you a list of users registered on your WordPress site. Locate the user you wish to remove. Click on the Delete link below the username of the person you want to remove.

      Administrador

    • JGUISS says

      JGUISS

      Didn’t worked for me…
      It’s worked with that : add_filter(‘show_admin_bar’, ‘__return_false’);

      how does the code look like with this added I’m not familiar enough with php to add it in

  24. The Little Binger says

    Hello!

    Thank you so much for being such a great help! I installed this code on the function file but it does not seem to work. I loaded my page on a different browser but the Log In bar is still there. Why is that? I also read your article about adding codes to the PHP file.

    I hope you could help me out on this. Thanks!!

  25. Vic says

    Hi! First of all, thanks for these codes, it’s very helpful, provided I considered myself not a first timer anymore who remember to add after the codes!
    I locked myself at the first time trying to add the php coding in my functions.php file as well, thanks to the “expert” web developer who didn’t show the full set of codes for a function. And thanks to your “what to do when you are locked out of WordPress admin area” site, I found out why I was locked out in the first place! But it took me a downtime of 3 days to figure out how to use the FTP, which at the end failed to function, but my webhost Helpdesk suggested me to use the File Manager in their Control Panel instead! Luckily it works! Lessons learnt the hard way, but worth it.. :P
    Just a kind suggestion, since this site was supposed meant for “WPBeginner”, I think all of the WP users beginner would appreciate if full set of codes are provided, rather than every other person “shouting” in the comment section that “The codes didn’t work, and locked me out”, and then you have to advise them to read a full length of another tutorial how to unlock their website, even though yes, you wish to teach us “How to fish” instead of “Fish for us” every time!
    Anyway, thanks again and appreciate your efforts here in guiding us, the WP Beginners! :)

    • WPBeginner Support says

      Thanks for the feedback. We try to make code easy to paste and use. However, usually there is already code in your functions.php file, which may affect the end result. We are glad you found your way out. :)

      Administrador

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.