How to use the wp_get_archives function in your WordPress Themes.

It is very common to have an archive in your WordPress blog displaying a list of the months that you have created a post on your blog. This navigation is the result in most cases of the wp_get_archives function of WordPress. However you may not know that you can utilize this same function to display a list of your most recent posts or to display yearly archives, you can even display the number of posts in an archive if desired. These navigational links can be created by use of the type, limit, and show_post_count parameters that can be passed to the wp_get_archives function.

To get started lets look at each of these 3 parameters individually.

  • type – the type parameter is used to tell wordpress what type of archive you would like returned. The most commonly used values are “monthly” (the default), “yearly”, and “postbypost” which returns a list of your posts.
  • limit – the limit parameter is used to tell wordpress the max number of items you want returned in your archives.
  • show_post_count – this parameter as the name implies will cause the number of posts in each archive item to be displayed. So if your archive was “monthly” and you did 12 posts in December 2009 then 12 would be displayed in the link. Please note that on “postbypost” archives this has no effect

Now that you are familiar with the options lets assume you would like to display a Recent Posts archive where you have links to the last 5 posts you did. To do this you would edit the appropriate template file that you would want the list to be displayed in and call the wp_get_archives function with limit=5 and type=”postbypost”. The exact code would look like the following.


If you wanted to display the last 12 months in your monthly archive and the number of posts you would set a limit=12 and show_post_count =1. As type is defaulted to monthly you would not have to specify that value. The end template code would possible look like:


That is all there is to it. There are additional options that you can set to modify the output or to return the archive as a string rather then echoing out the value as well. For full documentation on the function go visit the WordPress Codex wp_get_archives page.

Resources

// PHP // WordPress (WP) //

Comments & Questions

Add Your Comment