Home > Tips and Tricks, Wordpress > Creat an “Archives” Page in Your WordPress Blog

Creat an “Archives” Page in Your WordPress Blog

[ Note: You need to have “Exec-PHP” plugin activated in order for the code in this post to work. ]

I planned to create an “Archives” page in my blog. On this “Archives” page, I wanted to list all my posts and organize them in categories. In each category, posts would be sorted by date.

Obviously I needed to write some PHP code and use a few WordPress functions to achieve this goal. The first step was to retrieve all the categories from my blog. This was done using get_categories() function:

$categories = get_categories('orderby=name');
foreach ($categories as $cat)
    echo $cat->cat_name;
    echo ' (';
    echo $cat->category_count;
    echo ')';
    echo '<br />';

For every category retrieved from my blog, I needed to get all the posts in that category and list them in a table. To do this, I needed to create my own “Loop” in my code. There is a post on BlogChemistry.com talking about creating customized “Loop” in three ways. The first two methods, which involve using query_posts() and get_posts(), did not work for me. When I tried them, for some reason, the_permalink() and the_title() functions did not return the permalinks and the titles of the posts. Instead, they only returned the permalink and the title of the page -:( The third method involves using WP_Query class, which worked nicely for me. There is another good article on WP_Query.

To create a customized “Loop”, I made an instance of the WP_Query class and did it from scratch:

$my_query = new WP_Query($query_string);
if ($my_query->have_posts())
    while ($my_query->have_posts())
        echo the_permalink();
        echo the_title();

After adding some HTML formatting tags and putting all together, I got the complete source code for my “Archives” page:


  1. No comments yet.
  1. No trackbacks yet.