WordPress: yearly archives in the dynamic menu

The goal.

I was updating my WordPress theme yesterday and found out that there was no configuration-only method to display the archives list grouped by years, not months (default). After some source code analysis and web research, I found a nice way to do this. I will share it here, in two languages, so that other people don’t have to spend the time I spent on it (it was fun anyway).

If you do a few searches in the WordPress’ PHP source code, you will find that widgets like “Archives” are loaded in the file wp-includes/default-widgets.php. If you change this line:

<?php wp_get_archives(apply_filters('widget_archives_args', array('type' => 'monthly', 'show_post_count' => $c))); ?>

to:

<?php wp_get_archives(apply_filters('widget_archives_args', array('type' => 'yearly', 'show_post_count' => $c))); ?>

It will work. But, hey, that is a bad hack. Notice the path of the file you are editing: wp-includes/default-widgets.php. It is not inside your themes folder. This means your new archive menu will disappear next time you update your WP installation. To prevent that, you can take advantage of the hook mechanism provided by WordPress. The goal of this mechanism is exactly to expose some extension points which can be used by plugin and theme developers, so that they do not need to hack into WordPress’s engine code.

The Archives widget provides the “widget_archives_args” hook (available on WP >= 2.8). You can hook your function to it, and the function will be used as a filter for the parameters passed to wp_get_archives by the widget implementation. In this interception, you can change the archive type to “yearly” using the following snippet:

function yearly_archives_callback($args) { $args['type'] = 'yearly'; return $args; }
add_filter('widget_archives_args', yearly_archives_callback);

Put it at the beginning of your theme’s function.php file. In your sidebar, the Archives widget will now show a listing of years and, if you configured it to do so, the number of posts in that year. Since the file functions.php is inside your theme’s directory, you will not be overridden in a release update. You just have to take care not to use the default theme (twentyten) without renaming it, otherwise the effort to put the code inside a theme will have been worthless.

Este post também está disponível em português.

Esta entrada foi publicada em etc. Adicione o link permanente aos seus favoritos.

Uma resposta para WordPress: yearly archives in the dynamic menu

  1. Pingback: Wordpress: arquivos anuais no menu dinâmico | Subterfúgios

Deixe uma resposta

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.