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 adicionar um widget do WordPress ao cabeçalho do seu site (2 maneiras)

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 adicionar um widget do WordPress à área de cabeçalho do seu site?

Os widgets permitem adicionar facilmente blocos de conteúdo a seções específicas do seu tema, mas nem todos os temas incluem uma área de widget de cabeçalho.

Neste artigo, mostraremos como adicionar facilmente um widget do WordPress ao cabeçalho do seu site.

How to add a WordPress widget to your website header (2 ways)

Por que adicionar um widget de cabeçalho ao seu site WordPress?

O cabeçalho do site é uma das primeiras coisas que os visitantes verão ao acessar seu site WordPress. Ao adicionar um widget do WordPress ao seu cabeçalho, você pode otimizar essa área para ajudar a captar a atenção do leitor.

A maioria dos cabeçalhos de sites inclui um logotipo personalizado e um menu de navegação para ajudar os visitantes a navegar pelo site.

Você também pode adicionar um widget de cabeçalho acima ou abaixo dessa área para apresentar conteúdo útil, anúncios em banner, ofertas por tempo limitado, formulários de linha única e muito mais.

Aqui no WPBeginner, temos uma chamada para ação no cabeçalho diretamente abaixo do menu de navegação.

Header CTA example

A maioria dos temas do WordPress tem áreas prontas para widgets nas áreas da barra lateral e do rodapé do site, mas nem todos os temas adicionam áreas prontas para widgets no cabeçalho.

Nota do editor: Se o seu tema não tiver uma área de cabeçalho pronta para widgets, agora você pode criar temas do WordPress totalmente personalizados do zero (sem nenhuma codificação).

Mas, primeiro, vamos dar uma olhada passo a passo em como adicionar um widget do WordPress ao cabeçalho do seu site em seu tema existente. Basta usar os links rápidos abaixo para ir direto ao método que você deseja usar:

Método 1: Adicionar um widget do WordPress ao cabeçalho de seu site nas configurações do tema do WordPress

Muitos dos melhores temas do WordPress incluem uma área de widget de cabeçalho que você pode personalizar a seu gosto.

Primeiro, você deve verificar se o seu tema atual do WordPress suporta uma área de widget do WordPress no cabeçalho.

Você pode encontrar isso acessando o personalizador de temas do WordPress ou a área de widgets do painel de administração do WordPress. Para isso, navegue até Appearance ” Customize e veja se há uma opção para editar o cabeçalho.

Observação: se você estiver usando um tema de bloco, não verá essa opção na barra lateral do administrador. Em vez disso, consulte nosso guia sobre como personalizar seu cabeçalho usando o WordPress Full Site Editor.

Neste exemplo, o tema gratuito Astra tem uma opção chamada “Header Builder”. Mostraremos como usar esse recurso no Astra, mas lembre-se de que ele terá uma aparência diferente dependendo do tema que você estiver usando.

Astra header builder

Se você clicar nessa opção, será exibida uma tela para editar o cabeçalho e adicionar widgets.

Na parte inferior da tela, você pode personalizar completamente o cabeçalho, juntamente com as áreas acima e abaixo do cabeçalho. Basta passar o mouse sobre uma das áreas vazias e clicar no ícone “Mais”.

Click plus icon

Isso abre um menu pop-up no qual você pode selecionar “Widget 1”.

Há outras opções para escolher, mas você precisará selecionar uma das opções “Widget” para tornar o cabeçalho pronto para widgets.

Select widget 1 option

Para adicionar uma área de widget ao seu cabeçalho, clique na caixa “Widget 1” que está na seção do personalizador de cabeçalho.

Isso abre a opção de adicionar um widget.

Click widget 1 box

Em seguida, clique no ícone de adição de bloco “Plus” no menu à esquerda.

Isso abre uma janela pop-up na qual você pode selecionar um widget para adicionar ao cabeçalho.

Click plus icon and select widget

Você pode continuar a personalizar o cabeçalho e adicionar quantos widgets desejar.

Quando terminar, certifique-se de clicar no botão “Publicar” para salvar suas alterações.

Publish header widget changes

Agora, você pode visualizar a área do cabeçalho com o widget ou widgets que adicionou.

Aqui está uma captura de tela de como ela aparece em nosso site de demonstração.

Header widget example

Não está usando o Astra?

Outra maneira de verificar se o seu tema já tem um widget de cabeçalho do WordPress é acessar Appearance ” Widgets no painel de administração do WordPress.

Em seguida, veja se há uma seção de widget chamada “Header” (Cabeçalho) ou algo semelhante.

Go to widgets section for header widget

Se houver, basta clicar no ícone de bloco de adição “Plus” para abrir o menu de widgets.

Em seguida, você pode adicionar o widget que desejar clicando nele.

Header widget section

Certifique-se de clicar no botão “Update” (Atualizar) para salvar suas alterações na área do widget de cabeçalho.

Método 2: Adicione um widget do WordPress ao cabeçalho do seu site adicionando código ao WordPress

Se o seu tema do WordPress não tiver uma área de widget do WordPress no cabeçalho, você precisará adicioná-la manualmente, acrescentando código ao WordPress.

Se você nunca fez isso antes, consulte nosso guia sobre como copiar e colar código no WordPress.

Em seguida, você pode adicionar o seguinte trecho de código ao seu arquivo functions.php ou usar um plug-in de trechos de código, como o WPCode (recomendado):

function wpb_widgets_init() {

	register_sidebar( array(
		'name'          => 'Custom Header Widget Area',
		'id'            => 'custom-header-widget',
		'before_widget' => '<div class="chw-widget">',
		'after_widget'  => '</div>',
		'before_title'  => '<h2 class="chw-title">',
		'after_title'   => '</h2>',
	) );

}
add_action( 'widgets_init', 'wpb_widgets_init' );

Para obter mais detalhes, consulte nosso guia sobre como adicionar códigos personalizados no WordPress sem danificar seu site.

Ele o guiará pelo método WPCode.

Adding the Code Snippet to WPCode

Esse código registra uma nova barra lateral ou uma área pronta para widgets para o seu tema.

Se você acessar Appearance ” Widgets, verá uma nova área de widget denominada “Custom Header Widget Area”.

Custom header widget area

Agora, você pode adicionar seus widgets a essa nova área. Para obter mais detalhes, consulte nosso guia sobre como adicionar e usar widgets no WordPress.

No entanto, seu widget de cabeçalho ainda não será exibido ao vivo em seu site. Mostraremos como fazer isso a seguir.

Exibindo seu widget de cabeçalho personalizado no WordPress

Agora que você criou a área do widget de cabeçalho, é necessário informar ao WordPress onde exibi-lo em seu site.

Para fazer isso, você precisa editar o arquivo header.php do seu tema. Em seguida, você precisa adicionar o seguinte código onde deseja que o widget seja exibido:

<?php

if ( is_active_sidebar( 'custom-header-widget' ) ) : ?>
    <div id="header-widget-area" class="chw-widget-area widget-area" role="complementary">
	<?php dynamic_sidebar( 'custom-header-widget' ); ?>
    </div>

<?php endif; ?>

Esse código adicionará a área do widget personalizado que você criou anteriormente à área do cabeçalho do site.

Agora, você pode visitar seu blog do WordPress para ver a área do widget de cabeçalho ao vivo.

Header widget live

Estilize sua área de widget de cabeçalho do WordPress usando CSS

Dependendo do seu tema, talvez também seja necessário adicionar CSS ao WordPress para controlar como a área do widget de cabeçalho e cada widget dentro dela são exibidos. Isso pode ser feito de algumas maneiras:

Para saber mais, consulte nosso guia sobre como adicionar facilmente CSS personalizado ao seu site WordPress.

Neste artigo, daremos uma olhada rápida em como adicionar CSS personalizado usando o plug-in WPCode e o WordPress Theme Customizer.

No Método 2 acima, mostramos como usar o WPCode para adicionar um trecho de código ao seu arquivo functions.php. Você também pode adicionar esse plug-in para adicionar CSS personalizado.

Quando você criar um novo snippet no WPCode, certifique-se de selecionar o tipo de código “CSS Snippet” no menu suspenso à direita e de que a opção “Auto Insert” esteja selecionada.

CSS Code Snippet in WPCode

Na seção de visualização de código, é necessário adicionar o CSS para estilizar o widget de cabeçalho.

Aqui estão alguns exemplos de código CSS para ajudá-lo a começar:

div#header-widget-area {
    width: 100%;
    background-color: #f7f7f7;
border-bottom:1px solid #eeeeee;
    text-align: center;
		padding: 20px;
}
h2.chw-title {
    margin-top: 0px;
    text-align: left;
    text-transform: uppercase;
    font-size: small;
    background-color: #feffce;
    width: 130px;
    padding: 5px;
    }

Depois disso, certifique-se de que a configuração “Active” esteja ativada e, em seguida, clique no botão “Save Snippet” (Salvar snippet) no canto superior direito da tela.

Para usar o personalizador de temas, navegue até Appearance ” Customize (Aparência ” Personalizar ) no painel de administração do WordPress. Isso abrirá o painel do personalizador de temas do WordPress. Você precisa clicar na guia “CSS adicional”.

WordPress customizer additional CSS

Isso permite que você adicione CSS diretamente ao seu tema e veja as alterações em tempo real.

Basta adicionar o código CSS que mostramos acima à caixa “CSS adicional”.

Add CSS code and publish

Quando terminar de adicionar seu CSS, certifique-se de clicar no botão “Publish” (Publicar) para salvar suas alterações.

Esta é a aparência do widget de cabeçalho personalizado com as alterações no CSS.

Header widget example after CSS

Esperamos que este artigo tenha ajudado você a aprender como adicionar um widget do WordPress ao cabeçalho do seu site. Talvez você também queira ver nosso guia sobre como escolher a melhor hospedagem WordPress e nossas escolhas de especialistas sobre o melhor software de bate-papo ao vivo 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

83 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. Rob Hartman says

    This tutorial was PERFECT and I’ve successfully created the header widget, super light and no impact on page speed. I had hoped that I could use the same approach to add a widget area to my footer, and replace all Header related reference in both the Functions and footer.php – but in this instance the widget area was not registered.

    Does this approach ONLY apply to the header area?

    Regardless, thanks for a super concise tutorial.

    • WPBeginner Support says

      The code should work even in a footer but your theme may not display the footer on every page as a common reason.

      Administrador

  3. Sjoerd says

    Hi! Thanks for the tutorial. What if I want to show the widget area above the primary menu instead of right below it?

    • WPBeginner Support says

      That would depend on your specific theme, we would first recommend reaching out to your specific theme’s support to see if they have a built-in method for what you’re wanting to do or have recommended settings.

      Administrador

  4. Muhammad Kashif says

    Hello, I added the custom header widget successfully, but after updating the theme my custom header widget is not working ? Please tell me the solution! Looking forward to your response. thanks

  5. Vildan says

    Hi WP Beginner,

    How do I get the widget area in the header on the right side of the menu? I want to add the ADD TO CART icon in there.

    • WPBeginner Support says

      For placement, it would depend on the specific theme you are using, if you check with your theme’s support they should be able to let you know what part of your header.php file to add the code to or if they have a built-in method to do so.

      Administrador

  6. Bathri Vijay says

    Thank You WPBeginner Editorial Team giving a perfect blog to the beginners and middle class coders. It is a big platform to learn and to execute WordPress. You were the big reason for the success of many bloggers and business owners.

  7. zambol says

    Thanks for the tutorial. it works but the trouble I have is that it’s not responsible for mobile devices. is it possible to make the sidebar responsible?

    • WPBeginner Support says

      I believe you mean responsive in which case, we sadly do not have a recommended method for making this widget responsive at the moment.

      Administrador

    • WPBeginner Support says

      Depending on your specific theme, if there is content before the header.php content, you would want to reach out to the theme’s support

      Administrador

  8. dav says

    hello,
    I would like to make an header like the one in the first picture on the top of this page ( the list 25 website).
    How can I make It?
    Please help me!

  9. GoosePT says

    Hello!

    Perfect tutorial.

    Im using it to create a Topbar, but im facing a problem the widgets (in my case 2) are one below the other.

    How can I make them to be displayed side by side?

  10. Mikhail Koval says

    What would I have to put in the header.php to ONLY show on the home page but not show on other pages?

      • Anna says

        Hi, this is really what I’m looking for and it would be great if I could get it to work! Creating the widget area works fine, displaying it does unfortunately not.. I would also like to display it only on the start page.
        I´m not sure
        1) where in the header file to put the display code
        2) where to put this “only-on-startpage”-code and what code goes on line 2
        I understand if my questions are too basic to bother with, but I would be really grateful if someone has time and patience for it anyway..:-) Thanks in advance!!

        • WPBeginner Support says

          Hi Anna,

          These are perfectly reasonable questions.

          1. You need to put the display code based on where you want to display the header widget. For example, your theme’s header.php file may have a section to display site title, logo, description, and navigation menus. They will probably be wrapped around div tags. You will put your header widget code before or after these areas. If you are unsure, you can place the code at the end of the header.php file.

          2. If you only want to display the widget area on your website’s front page then you can use conditional tags like this:

          if ( is_front_page() ) {
          // your widget display code goes here 
          
          } 
          
        • Anna says

          OK, I cheated and put the widget-code in the front-page.php instead, it worked! Thanks :-)!

    • Anna says

      Hi again, it became visible on start page with css positioning!

      Now it’s only the question of how to put together the only-on-start-page-code with the visibility code…

      Thanks again for kindness and patience..)

  11. Paul Johnson says

    Great tutorial thanks. I am trying to implement the JetPack Cookie Consent Widget and despite following your instructions the Cookie Consent bar still appears at the bottom of the page.

    Is it possible the widget is overriding the code?

  12. thomas evans says

    Hello
    pls can someone here help me as how to make this responsive on any mobile device?

    i want to insert a google adsense code here for ads 728 x 90 banner sizes but any time i do so, it shows perfectly on desktops but on mobile devices it becomes weird.
    thank you

  13. Anubhav Bhatt says

    I have successfully created a header widget and It was really easy, thanks to you all. But I actually wanted it in the POSTS, not on the Homepage because I’m using Nikko Portfolio theme and it looks awful.
    Please Help.

  14. Jeffrey says

    I placed the code in my functions.php file and added my widget code in the header.php file and added my widget text and saved.
    When I move on to editing pages, upon clicking Update, I get a white screen and can’t see my page.
    I then have to go back to /wp-admin to see the dashboard. There are no console errors when I click update but just a white screen.

  15. Derek says

    This is great for that header advertizment thing, but what I want to do is add a pay pal donation button to my header. (Right side) cant believe there is no video tutorials out there on how to make a a widgetized header space to drag your pay pal widget into so that it appears on the right side of your header.. i can imagine there is alot of people who could benefit from an instructional on this.

  16. Stephen Crawford says

    This is a great tutorial, but I would like to create a widget area that can be placed above the header area would that also be possible?

  17. Joey says

    Just updated everything and it’s working great on my desktop. Now, if you could tell me how to get the widget to display on my mobile device that would be great! Did I mess something along the way?

  18. Mark says

    Hi, many thanks for writing this, it has helped me massively. However, with my website: how do I get the widget to appear at the far right hand side. When I use the option to show search field in the header, this is the place I want it to go?

    Thanks in advance! :)

  19. Linda Holiner says

    I am confused. I don’t understand how to get an image into the widget and let the user change the image. I don’t see where your image is coming from.

  20. Thomas says

    Would it be possible to make a tutorial about how to make a TopBar with sections (Social media icons, Notice, Search, Woocommerce cart).

    No plugin does really do that well

    Thanks

  21. Tim says

    If i want to add multiple custom widget areas do i need to add a new function to functions.php for each? or just add them in the area i want?

  22. fahad says

    I managed to use the widget in the navigation bar instead of the header area as I wanted to add a language toggle option at this section. I have a small problem where I can’t move the language two flags to the any horizontal location. I tried to add margin-right: 100px; to the advanced CSS section but it didn’t change. It might be something else centering all the navigation content but I want to make sure if it could be fixed with the widget.

    • Courtney says

      Hey how did you edit the code to put it in the nav bar? I’m currently trying to do the same thing without any luck.

  23. Leanore says

    When I attempt to add more than one custom widget area, I receive a 500 Error on my website. Is there a reason for this? Is it possible to create more than one custom widget area for a theme?

  24. nina says

    Hi! When i try to update the function.php file, there is this fatal error:
    Fatal error: Cannot redeclare wpb_widgets_init()
    I am not sure if i did a wrong edit. Could you help

    • WPBeginner Support says

      Hey Nina,

      This means that wpb_widgets_init function already exists in your functions.php file. You will have to replace it like wpb2_widgets_init to make it unique or remove the previous code that you added.

      Administrador

  25. Sam says

    Hello,

    Thanks so much for this, it is really helpful.

    One issue I am running into: My widget is just a menu of a couple of text links to pages. Here is my site:

    See how the text is all the way against the right side of the header area? I would like to use a right margin to line it up under “Contact” without turning the margin area white.

    Also, would love to make the text black. :)

    Many thanks if you can help with these tweaks!

    Sam

  26. Tommy says

    Your blog is most helpful. Thank you for helping us made modifications to Twenty Seventeen. People like you make using a new wordpress theme like Twenty-seventeen much easier.

    I am relatively new to word press and would like to try some additional modifications to Twenty seventeen.

    I would like to create a new widget for wp pages. I am trying to figure out how I can take your blog information on how to make a new widget for the header and apply it to a wp page in the twenty seventeen theme. I am getting stuck.

    Could you show us now to create a new widget for a page? That would be awesome.

    Thanks
    Tommy

  27. Bobby_qw says

    Thank you very much Mr. Admin.You are teahing to us ‘how to make our own web site. l always follow your posting and l make my own web site. Thank you very much.

  28. Shane Cunningham says

    I used this and though it worked in adding a custom widget area to the top of my page, i could not get it to align with the other items in the header (company logo and nav menu) in Cherry. No matter where I put it in the header.php, it either appeared above or below the other items. I wanted to use it to create a phone number block between the logo and the nav menu. Though I could get it to center in correct spot horizontally, i could not get it to appear between them. To give you a better idea of what I need, imagine that on this very page’s header, you wanted to move the nav menu justified to the right and put your 800 number between it and the “wpbeginner” logo. How could I use this code (or a variation of it) to do that?

  29. Kristin says

    Thank you so much for this (and all) of your detailed tutorials! Could you please tell me how to implement a header widget, excluding the Homepage?

    • Massimo says

      In the code that you added to header.php change the first line:
      if ( is_active_sidebar( 'custom-header-widget' ) ) : ? >
      with this one:
      if ( is_active_sidebar( 'custom-header-widget' ) && ! is_front_page ) : ?

    • Massimo says

      Sorry, I missed something!
      The line that you have to add is:
      if ( is_active_sidebar( 'custom-header-widget' ) && ! is_front_page() ) : ?>

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.