X

Añada un pie de página con widgets a su tema de WordPress

La inspiración para este tutorial viene de un tuit que recibí con comentarios para el tema RS12 que pronto saldrá a la venta.

zakmorris twitter response

Aunque el pie de página con widgets no se incluyó finalmente en la versión del tema RS12, decidí escribir este tutorial para mostrar a la gente cómo añadir exactamente un pie de página con widgets en tu tema. En esta guía, aprenderás:

  • El código HTML y CSS necesario para producir el pie de página widgetizado
  • Cómo añadir etiquetas de plantilla de WordPress de uso común como marcadores de posición
  • Cómo widgetizar el pie de página y colocar widgets en su interior

Va a haber mucho código en este post, así que si te apetece, sigue leyendo…

Usaré el tema de WordPress Green Rays como ejemplo en este tutorial. Por el momento, el pie de página sólo tiene un mensaje estándar de “copyright” y créditos.

El HTML

El primer paso es añadir el código HTML. Digamos que vamos a tener tres secciones diferentes en el widgetized footer con listas de Most Recent Posts, Monthly Archives, y Daily Archives. Colocaremos este código HTML encima de la línea “copyright” actual.

<div class="footer-item">
<h3>Publicaciones recientes</h3>
<ul>
<li><a href='#' title='Post destacado'>Post destacado</a></li>
<li><a href='#' title='Citas en bloque'>Citas en bloque</a></li>
<li><a href='#' title='Cómo funciona la etiqueta 'más'>Cómo funciona la etiqueta 'más'</a></li>
<li><a href='#' title='Ordenar o desordenar'>Ordenar o desordenar</a></li>
</ul>
</div>
<div class="footer-item">
<h3>Archivos del mes</h3>
<ul>
<li><a href='#' title='Marzo 2008'>Marzo 2008</a></li>
<li><a href='#' title='febrero 2008'>febrero 2008</a></li>
<li><a href='#' title='Enero 2008'>Enero 2008</a></li>
<li><a href='#' title='Diciembre 2007'>Diciembre 2007</a></li>
</ul>
</div>
<div class="footer-item">
<h3>Archivos diarios</h3>
<ul>
<li><a href='#' title='7 de marzo de 2008'>7 de marzo de 2008</a></li>
<li><a href='#' title='9 de febrero de 2008'>9 de febrero de 2008</a></li>
<li><a href='#' title='4 de enero de 2008'>4 de enero de 2008</a></li>
<li><a href='#' title='22 de diciembre de 2007'>22 de diciembre de 2007</a></li>
</ul>
</div>
<div class="clear"></div>

Básicamente este código pone cada “widget” en un div. Dentro de cada widget hay un encabezado y una lista desordenada con enlaces. Sí, ya sé que los enlaces no van a ninguna parte. Más tarde reemplazaremos esto con etiquetas de plantilla de WordPress. Esto es lo que tenemos hasta ahora:

Green Rays Footer 1

El CSS

Como puedes ver, esto no se ve tan bien sin ningún estilo CSS. Añade el siguiente código a tu hoja de estilos.

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

Lo que hace este código es flotar cada elemento de pie de página a la izquierda, lo que básicamente significa que pueden estar uno al lado del otro. El ancho se establece en 33%, lo que da suficiente espacio para tres elementos de pie de página en una sola fila. También hay un poco de relleno añadido debajo de cada elemento de pie de página. La segunda pieza es sólo el relleno de las listas de 15 píxeles a la izquierda.

Ahora puedes ver que el HTML y el CSS están empezando a encajar. Esto es lo que deberías tener hasta ahora:

Green Rays Footer 2

Código WordPress

Por el momento, tenemos un montón de enlaces HTML vacíos, sin código real de WordPress. Reemplacemos las listas de Entradas Recientes, Archivos Mensuales y Archivos Diarios con las etiquetas de plantilla equivalentes de WordPress. Reemplace lo que tiene actualmente con lo siguiente:

<div class="footer-item">
<h3>Publicaciones recientes</h3>
<ul>
<?php wp_get_archives('type=postbypost&limit=4'); ?>
</ul>
</div>
<div class="footer-item">
<h3>Archivos del mes</h3>
<ul>
<?php wp_get_archives('limit=4'); ?>
</ul>
</div>
<div class="footer-item">
<h3>Archivos diarios</h3>
<ul>
<?php wp_get_archives('type=daily&limit=4'); ?>
</ul>
</div>

Los parámetros deberían ser bastante autoexplicativos, pero si no estás seguro de alguno de ellos, intenta buscar wp_get_archives en la herramienta de búsqueda de etiquetas de plantillas de WordPress. Recuerde, sólo estoy usando las etiquetas de plantilla wp_get_archives() como marcador de posición. Las cambiaremos por otros widgets de WordPress más adelante, después de widgetizar el pie de página.

Widgetízalo

Para esta sección del tutorial, tomaré prestadas algunas partes de mi tutorial anterior sobre widgetización de temas.

El primer paso es registrar las “barras laterales”. Para hacer esto, simplemente reemplace el contenido actual del archivo functions.php con lo siguiente:

<?php
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Sidebar',
'before_widget' => '<div class="sidebaritem">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Pie de página',
'before_widget' => '<div class="footer-item">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
?>

Ahora iremos a sidebar.php y sustituiremos la etiqueta condicional de la barra lateral dinámica actual por esto:

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

Con esto:

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

Ahora vamos a ir a nuestro archivo footer.php y envolver los elementos de pie de página en su propia etiqueta condicional respectiva barra lateral. Justo antes del primer div “sidebar-item”, añade lo siguiente.

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

Justo después del último div “footer-item” de cierre (y encima del div “clear” que hemos añadido antes) añadiremos lo siguiente:

<?php endif; ?>

Bien, ahora nuestra barra lateral y pie de página deberían estar widgetizados. Vamos a probarlo añadiendo algunos widgets en el pie de página. Añadiré un widget de Blogroll, un widget de Comentarios recientes y un widget de texto. Esto es lo que debería parecer:

Green Rays Footer 3

Conclusión

Bueno, esto es lo básico para añadir un pie de página con widgets a tu tema. Puede que quieras añadir reglas de estilo separadas para otros tipos de widgets como el calendario o la caja de búsqueda. Esto probablemente no funcionará con todos los temas, como el tema RS12 por ejemplo, ya que tenía un pie de página no expandible.

Si por casualidad alguien quiere el tema actualizado de Green Rays, puede descargarlo aquí. De esta manera se puede ver dónde exactamente he añadido el código. También se puede comparar con el tema original.

Espero que os haya gustado el tutorial. ¿Vas a añadir un pie de página con widgets a tu tema? ¿Hay algo en el código que usé arriba que harías diferente? Preguntas, comentarios, sugerencias y críticas son bienvenidas, así que siéntete libre de opinar en los comentarios.

Comentarios   Deja una respuesta

  1. I am having an error while adding a custom widget in my theme. This is the code that I have been adding in functions.php.

    function widget()
    {
    register_sidebar(array(
    ‘name’ => __(‘Primary Sidebar’, ‘wpb’),
    ‘id’ => ‘primary_sidebar’
    ‘description’ => ”,
    ‘class’ => ”,
    ‘before_widget’ => ”,
    ‘after_widget’ => ”,
    ‘before_title’ => ”,
    ‘after_title’ => ”,
    ));

    }
    add_action(‘widgets_init’, ‘widget’);

    1. What error message are you receiving?

  2. Amazing job on your tutorial!

    One question:

    Why did you need to add code into the sidebar.php file when the purpose of the tutorial is adding three widgetized areas into the footer?

    1. Hey Mark, good question.

      This tutorial assumes you already have a widgetized area in your sidebar. When I mention the sidebar.php file, I’m basically recoding that widgetized area to have a unique name (in this case, “Sidebar”) to differentiate it from the new widgetized footer area we’re about to create.

      There’s more info on coding multiple widget areas in my WordPress theme widgetizing tutorial.

  3. Wow, I actually got this to work! (Not a comment on your code, just a comment on my coding prowess). Thanks!

  4. My first attempt at widgetization, and this worked absolutely perfectly. Thank you! 🙂

  5. You said:
    “The first step is to add the HTML markup.” and “We’ll place this HTML code above the current “copyright” line.”

    OK…. add it to WHAT? Where do I put the html markup? What do I add it to? How do I find the file that has the “copyright” line?

    1. Try looking in your footer.php file.

      1. Could you give me a quick rundown on the new 2012 default theme footer? I want to use this tutorial but the 2012 foot is freakishly long or “High” I want to ad 5 text widgets, and it has fluid template, i use the Full Page Template so i would like it centered. You can throw in a bag of chips with that if you like 😛

  6. The tutorial is wonderful, but I would like to know how to colorize the background where the widgets stand or how to add an image under them. If you could reply to this comment or send me an e-mail it would be great.
    Once again, great tutorial it worked perfectly for my theme’s blog and now I want just to paint it a little, if you know I mean.
    Kind regards and I am waiting for a reply from your part! 🙂

    1. I think you’re looking for the CSS background property – http://www.w3schools.com/css/css_background.asp

  7. Wow, I really don’t know that you could have made that more straightforward and simple. Excellent tutorial on a process that could have been much more difficult…10 mins and I’m up and running with brand new footer widgets. Thanks!

  8. Thanks a lot for taking the time out to do this! awesome post. The theme I am working with has been customised a lot so this should help me add the footer i’ve been after for a while!

  9. Thanks for the great tutorial. I do have one question. Adding the widgets is not a problem but somehow he doesn’t want to add a background to the whole footer. The part where the widgets are stays white with me. Anyway to fix that?

    http://blog.whenlovefalls.com/

    1. Hmm…seems I forgot to mention putting .clear { clear: both; } in your stylesheet.

      That should fix the problem.

  10. Isn’t it a problem to just replace the contents of the functions.php file? Isn’t that one of the files I’m not supposed to touch?

    Also — what function call would I need in order to get a list of pages in each section of the website? I want a sort of “site map” footer, if you know what I mean (a horizontal list of top level links, each with its sub-pages listed below)

    1. You can touch it if you want but I’d make a backup before editing it as if you make a mistake, it can cause problems for the rest of your site.

      You’re probably looking for the wp_list_pages function or the “Pages” widget.

  11. This post saved me. I tried so many other posts, I almost gave up and then I found yours. It works like a charm. Being a San Diego Personal Trainer, I have to be able to have info right there for people. Thanks again for the help. 2001 Iron

    1. Sorry, hit the submit button accident. Okay, thanks for the killer post. Do you mind if I put up a link for it. Thanks

      2001 Ironman Bodybuilding Champion, Hank Butler

      1. Glad you liked the post, Hank. Feel free to link back to it.

  12. Can i replace this footer with any wordpress themes’s footer

    1. Pretty much. There are some footer designs that aren’t very flexible though and it might not work on those.

  13. Hi Leland,
    How can i change it so that the background of the entire footer is a different color than the rest of the page? I tried using background-color in the footer-item section of the style sheet but it will only change the background of the areas occupied by widgets e.g. if the widget only occupies half of the widget area, the background too is only occupies half of the area.

    1. You would probably need to put another div around all the footer-item divs and set the background-color to that. Make sure the footer-item divs are cleared as well.

      1. Thanks Leland
        I played around some more and was able to get it done. I had to put my tag at the beginning of the file and place the background-color style within it.

  14. Thanks for the post. I tried so many other peoples ideas on how to do this and pretty much spent most of my time fixing what they had srewed up. This works like a charm and now I have it on all of my sites. Thanks

    1. Hank, glad to hear it worked for you!

  15. Thank you so very much for this nice tutorial, Leland! 🙂

    Do you think you could guide me about how I could add separators between each block (div) of links or widget, as in the footer of this page?

    1. @Saeed: All you’d need to do is change your CSS.
      You could do something like:
      .footer-item { border-right:1px solid #000; }
      Or you could always apply a background to each footer item.

      @Leland: Stumbled upon this post, trying to do something a little extended and was looking for advice. Say the user wants to add more than 3 widgets (for example) and the width of the footer container can only handle 3. I want the next 3 widgets to drop directly below. Where I’m getting stuck is that when the 4th (and on) widgets are added, that they are not vertically aligned properly… because of the top 3 widgets not having a fixed height. But I don’t want the widgets to have a specific height, I want it to be dynamic.

      The only thing I can think of is to have a function grabbing widgets for the footer in groups divisible by 3, and wrapping them in a div container. Can you help with that? If not, do you have any other suggestions how I can tackle this?

      Thanks,
      Jeff

      1. Jeff, what I would do is make three separate widget areas, one for each column. That way you could put as many widgets as you want in each column and they would be aligned properly.

        1. Great idea! Thank you

  16. Hi

    I can seem to get through the widgetizing part of the tutorial. And now my site is plagued with errors. I followed the steps exactly how you explained them.

    Can you write back so we can go over what went wrong?

    Thanks for making this tutorial. I’m looking forward to making this work for my site. It is a good idea.

  17. Nice tutorial. I am also stuck on the widgetizing part. I have multiple sidebars in my site so I have two sidebar.php files. I tried adding the sidebar HTML to my “sibebar1.php” file, but now I get an error similar to what others have posted.

    what am I doing wrong?

  18. Really great article, finally its worked for me, Now its implemented in my site, Its helped me to design existing theme as i like instead of searching for suitable theme. Once again thanks for giving this.

  19. Hello, Could I use this with Thesis Theme? I purchased it and I am trying to learn how to use all it’s features such as Thesis OpenHook. Let me know.

    Thanks, Tam

  20. Add a Widgetized Footer to Your WordPress Theme | Theme Lab | Squico julio 29, 2009 en 6:00 am

    […] In: WordPress plugins 29 Jul 2009 Go to Source […]

  21. 5 Useful And Creative Ways To Use WordPress Widgets | SEO & Web Design julio 21, 2009 en 2:38 am

    […] Add a Widgetized Footer to Your WordPress Theme A tutorial that teaches you how to cipher your possess widgetized footer, including the HTML, CSS and WordPress cipher needed. […]

  22. 5 Useful And Creative Ways To Use WordPress Widgets | julio 19, 2009 en 2:40 am

    […] Add a Widgetized Footer to Your WordPress Theme A tutorial that teaches you how to code your own widgetized footer, including the HTML, CSS and WordPress code needed. […]

  23. 5 Useful And Creative Ways To Use WordPress Widgets | Design Visibility julio 17, 2009 en 8:01 pm

    […] Add a Widgetized Footer to Your WordPress Theme A tutorial that teaches you how to code your own widgetized footer, including the HTML, CSS and WordPress code needed. […]

  24. Leland:

    Thanks for your comment on my post. My only problem with this tutorial is I don’t know where the initial “HTML” markup goes. Is it in the functions.php?

  25. S.P. Sullivan Media | Wants to borrow your parents’ car» Blog Archive » #CSSfail. junio 21, 2009 en 5:05 pm

    […] a widgetized footer on a minimalist WordPress theme? I’ve already tried the tutorial here and some troubleshooting here. I might try this one […]

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!