X

Adicione um rodapé com widgets ao seu tema do WordPress

A inspiração para este tutorial vem de um tweet que recebi com comentários sobre o tema RS12 que será lançado em breve.

zakmorris twitter response

Embora o rodapé com widge não tenha sido incluído no lançamento do tema RS12, decidi escrever este tutorial para mostrar às pessoas como exatamente adicionar um rodapé com widge em seu tema. Neste guia, você aprenderá:

  • O código HTML e CSS necessário para produzir o rodapé com widge
  • Como adicionar tags de modelo do WordPress comumente usadas como espaços reservados
  • Como colocar widgets no rodapé e colocá-los dentro dele

Haverá muito código nesta postagem, portanto, se você estiver disposto a isso, continue lendo…

Neste tutorial, usarei o tema Green Rays do WordPress como exemplo. No momento, o rodapé tem apenas uma mensagem padrão de “copyright” e créditos.

O HTML

A primeira etapa é adicionar a marcação HTML. Digamos que vamos ter três seções diferentes no rodapé com listas de publicações mais recentes, arquivos mensais e arquivos diários. Colocaremos esse código HTML acima da linha atual de “copyright”.

<div class="footer-item">
<h3>Publicações recentes</h3>
<ul>
<li><a href='#' title='Postagem em destaque'>Postagem em destaque</a></li>
<li><a href='#' title='Blockquotes'>Blockquotes</a></li>
<li><a href='#' title='Como a tag 'more' funciona'>Como a tag 'more' funciona</a></li>
<li><a href='#' title='Order or Unorder'>Order or Unorder</a></li>
</ul>
</div>
<div class="footer-item">
<h3>Arquivos mensais</h3>
<ul>
<li><a href='#' title='Março de 2008'>Março de 2008</a></li>
<li><a href='#' title='February 2008'>February 2008</a></li>
<li><a href='#' title='January 2008'>January 2008</a></li>
<li><a href='#' title='December 2007'>December 2007</a></li>
</ul>
</div>
<div class="footer-item">
<h3>Arquivos diários</h3>
<ul>
<li><a href='#' title='March 7, 2008'>March 7, 2008</a></li>
<li><a href='#' title='February 9, 2008'>February 9, 2008</a></li>
<li><a href='#' title='January 4, 2008'>January 4, 2008</a></li>
<li><a href='#' title='December 22, 2007'>December 22, 2007</a></li>
</ul>
</div>
<div class="clear"></div>

Basicamente, esse código coloca cada “widget” em uma div. Dentro de cada widget há um título e uma lista não ordenada com links. Sim, eu sei que os links não vão a lugar algum. Mais tarde, substituiremos isso por tags de modelo do WordPress. Aqui está o que temos até agora:

Green Rays Footer 1

O CSS

Como você pode ver, a aparência não é tão boa sem nenhum estilo de CSS. Adicione o seguinte código à sua folha de estilo.

.footer-item {
float: left;
largura: 33%;
padding-bottom: 10px;
}
.footer-item ul {
padding-left: 15px;
}

O que esse código faz é flutuar cada item do rodapé para a esquerda, o que basicamente significa que eles podem ficar lado a lado. A largura é definida como 33%, o que dá espaço suficiente para três itens de rodapé em uma única linha. Há também um pouco de preenchimento adicionado abaixo de cada item de rodapé. A segunda parte é apenas o preenchimento das listas com 15 pixels à esquerda.

Agora você pode ver que o HTML e o CSS estão começando a se encaixar. Aqui está o que você deve ter até agora:

Green Rays Footer 2

Código do WordPress

No momento, temos um monte de links HTML vazios, sem nenhum código real do WordPress. Vamos substituir as listas em Posts recentes, Arquivos mensais e Arquivos diários pelos equivalentes da tag de modelo do WordPress. Substitua o que você tem atualmente pelo seguinte:

<div class="footer-item">
<h3>Publicações recentes</h3>
<ul>
<?php wp_get_archives('type=postbypost&limit=4'); ?>
</ul>
</div>
<div class="footer-item">
<h3>Arquivos mensais</h3>
<ul>
<?php wp_get_archives('limit=4'); ?>
</ul>
</div>
<div class="footer-item">
<h3>Arquivos diários</h3>
<ul>
<?php wp_get_archives('type=daily&limit=4'); ?>
</ul>
</div>

Os parâmetros devem ser bastante autoexplicativos, mas se você não tiver certeza sobre algum deles, tente procurar wp_get_archives na Ferramenta de pesquisa de tag de modelo do WordPress. Lembre-se de que estou usando as tags de modelo wp_get_archives() apenas como um espaço reservado. Vamos trocá-las por outros widgets do WordPress mais tarde, depois de colocarmos widgets no rodapé.

Colocar no widge

Para esta seção do tutorial, pegarei emprestadas partes do meu tutorial anterior sobre temas de widgetização.

A primeira etapa é registrar as “barras laterais”. Para fazer isso, basta substituir o conteúdo atual do arquivo functions.php pelo seguinte:

<?php
Se ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Sidebar',
'before_widget' => '<div class="sidebaritem">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
Se ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Footer',
'before_widget' => '<div class="footer-item">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
?>

Agora vamos para sidebar.php e substituiremos a tag condicional da barra lateral dinâmica atual por esta:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>

Com isso:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Sidebar") ) : ?>

Agora, entraremos em nosso arquivo footer.php e envolveremos os itens do rodapé em sua própria tag condicional de barra lateral. Logo antes da primeira div “sidebar-item”, adicione o seguinte.

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Footer") ) : ?>

Logo após o fechamento final da div “footer-item” (e acima da div “clear” que adicionamos anteriormente), adicionaremos o seguinte:

<?php endif; ?>

Pronto, agora nossa barra lateral e o rodapé devem estar com widgets. Vamos testá-los adicionando alguns widgets no rodapé. Adicionarei um widget de Blogroll, um widget de Comentários recentes e um widget de texto. Esta é a aparência que deve ter:

Green Rays Footer 3

Conclusão

Bem, esse é o básico para adicionar um rodapé com widgets ao seu tema. Talvez você queira adicionar regras de estilo separadas para outros tipos de widgets, como o calendário ou a caixa de pesquisa. Isso provavelmente não funcionará com todos os temas, como o tema RS12, por exemplo, pois ele tinha um rodapé não expansível.

Se, por acaso, alguém quiser o tema atualizado do Green Rays, poderá baixá-lo aqui. Dessa forma, você poderá ver onde exatamente adicionei o código. Você também pode compará-lo com o tema original.

Espero que você tenha gostado do tutorial. Você adicionará um rodapé com widgets ao seu tema? Há algo no código que usei acima que você faria diferente? Perguntas, comentários, sugestões e críticas são bem-vindos, portanto, sinta-se à vontade para falar nos comentários.

Comentários   Deixe uma resposta

  1. Leland,

    Here’s the pastebin link for my functions.php file. I posted it sans your alteration. Your help is appreciated.

    http://pastebin.com/m40073591

  2. “I too am trying to widgetize my footer using your step, but when I add the code to the functions.php, I keep getting the same error message:

    Parse error: syntax error, unexpected ‘}’ in /home/………..redacted………/functions.php on line 230

    I’m sure this means I just have a ‘}” out of place, but removing it doesn’t seem to work. Help?”

    I am experiencing the same problems. Could you offer some advice?

    Thanks,
    Dave

    1. did you ever figure that out? I’m also having the same problem but it happened when I changed my sidebar.php code.

      how did you fix it?

      I’m running 2 sidebars thus I have 2 sidebar.php files. I tried reverting the code to its original state but no dice. I guess I’ll have to upload my backup php file, but that will not solve the problem, it will only let me continue working on my site.

      if there’s any advice, I’d appreciate it.

      thanks

  3. Stumbled across this by accident – great tutorial in terms of both content and writing style – well done.

  4. Mega-Doodle Inspired junho 5, 2009 em 10:00 am

    This tutorial rocks my world! I have not seen such a thorough explanation of how to do this. I am in the process of creating a new look for my blog and wow…this is totally what I needed. Thank You so much!!

  5. links for 2009-05-31 » Von admin » Beitrag » von pixeln und paddeln maio 31, 2009 em 6:01 pm

    […] Add a Widgetized Footer to Your WordPress Theme | Theme Lab (tags: wordpress tutorial footer CSS) […]

  6. @Lance: It would depend on the theme, but it would be somewhere within the “footer” div (whatever it may be called).

    It looks like the footer on your site has a fixed height, so you’d probably have to fix that before using this code.

  7. Hi – Thanks for this turorial but I’m confused. Where do I put the HTML code that you have at the beginning?

    I have the css and the footer files and I know I can put the code in there. But where does the actual HTML code go?

  8. FreshPick - New free premium like theme - ReviewPk maio 11, 2009 em 3:18 pm

    […] box, custom archive and search templates, an options page, and four widgetized areas (including a widgetized footer). These features will be gone over […]

  9. @Terri: No problem! Nice widgetized footer, by the way. 🙂

  10. yyyyes! Thank you!

  11. @Hannah: Yes, that’s what it means. Although it’s kind of hard for me to diagnose the problem if I can’t see the exact code. Could you possibly paste the code of your current functions.php file to some sort of pastebin? Something like http://pastebin.com – thanks!

  12. Great tutorial! I’m trying to widgetize my footer using your step, but when I add the code to the functions.php, I keep getting the error message:

    Parse error: syntax error, unexpected ‘}’ in /home/………..redacted………/functions.php on line 230

    I’m sure this means I just have a ‘}” out of place, but removing it doesn’t seem to work. Help?

  13. Add a Widgetized Footer to Your WordPress Theme | Widgetifyr.com abril 28, 2009 em 9:58 am

    […] found a nice tutorial on how to add widgets to the footer of a theme. Widget aren’t just for the sidebar […]

  14. @ezg: Ah…well glad it worked out for you.

    @Jeffro: Thanks, appreciate the stumble, and glad you liked the tutorial.

  15. I’ve been waiting for a post like this for a long time now. I figured it out on my own but it’s always nice to have a reference to fall back on. I submitted this puppy to StumbleUpon 🙂

  16. links for 2009-04-27 « sySolution abril 27, 2009 em 10:00 am

    […] Add a Widgetized Footer to Your WordPress Theme | Theme Lab (tags: wordpress) […]

  17. Pardon the dust - WPMU Tutorials abril 27, 2009 em 9:31 am

    […] domain ), uploaded the new theme, and started making my tweaks to it. The biggest thing I did was add a chunky widgetized footer. You can do the same using the linked tutorial from Leland at Theme Lab. Mostly I wanted to make […]

  18. Monday Morning Roundup - April 27, 2009 — WPCandy — WordPress Themes, Plugins, Tips, and Tricks abril 27, 2009 em 6:04 am

    […] Add a Widgetized Footer to Your WordPress Theme – who says widgets are just for sidebars? I’ve seen them used in plenty of other places, including footers, which is exactly what you’ll learn to do in this tutorial. [Link] […]

  19. Erica’s Themes abril 26, 2009 em 3:56 pm
  20. You didn’t see it, cause I’m not using it now. But when I turned it on, it really looked like great. Later, when I will think about what widgets to use I’ll turn it on.

  21. @ezg: Nice! Just wondering, which blog did you use it on? I checked the URL you used to comment here, but didn’t see the widgetized footer.

  22. I used your tutorial in my blog. It looks really cool.
    Thanks for your lesson. 🙂

  23. @sriganesh: Sounds good, let me know how it works out for you.

    1. thanks. iam using now elegant theme.which i won in contest. see my theme footer.. thanks alot. , i mini problem-i added my flickr photos. but its irregularly arranged.like other professional site with border, i cant align it. can u help me in this. past three months i tried my own and added codings but nothing happen.

  24. Posts about Theme as of April 25, 2009 · Fee Premium Themes Wordpress abril 25, 2009 em 10:22 am

    […] HTML or for a content management system (CMS)? Depending on your skill Add A Widgetized Footer to Your WordPress Theme – themelab.com 04/25/2009 The inspiration for this tutorial comes from a tweet I received with […]

  25. nice tutorial, i’ll try this, cos i need something like that. visit my site. i like to have same as it mentioned here.

    1. Don’t get me wrong, I love the tutorial and all…but to be completely honest, I feel you kind of hoed us out…like we want to know how YOU did YOUR header you know? This is no personal attack, but I just feel a little jipped getting a measly boring text footer….

      If you could please, tell us how you did YOURS, that’d be great. And not just throw in “put your image behind it…” I mean how youuuuu did it for real. Thanks….

      1. I did all of what you said and I don’t know how to “drag” the widgets…? I don’t see anywhere to drag them to….

        1. You do that in your WordPress admin panel on the widget page. By “dragging” I just mean putting the widgets in the various widgetized areas.

          Sorry you feel “hoed out” but I wanted to write a tutorial that could apply to almost any kind of theme.

          FYI, I don’t even use any WordPress widgets in the footer and header of this site, they’re hardcoded.

    2. I’m not sure how much more detailed he could have been. If you’re a web designer and have an idea of what wordpress is, they you would know how to get the rest accomplished. His tutorial was perfect.

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!