Watkins Web 3: Blog

Cheat Sheet: a Wordpress archive page

Here’s a demo of a relatively simple archive page. (You might want to delete the page-archive.php file that came with your theme, since it uses a different function than the one we’ve discussed.

This method uses the function called get_posts(), described in the post about Wordpress Loops to work, you would do the following:

  1. In your theme folder, find page.php, duplicate it, and rename the copy to page-archive.php.
  2. Open the new page.archive.php file in Textwrangler and change the comment at the top to read exactly as it does in the example below. The crucial part is “Template Name: Archive page”, which Wordpress will use to recognize this file as a new page template.
  3. Copy the loop portion of the code below into your page-archge.php, save it, and upload it to your theme directory.
  4. In Wordpress, choose Pages > Add New. Title the new page “Archive” or something similar. In the Page Attributes pane, click the Template pop-up and choose your new template name (“Archive page” or similar). If you don’t see it listed, make sure you matched the comment syntax exactly as in the example below.
  5. Click Publish (or Update) and then View Page to view your archive.

Here’s an example of a straightforward archive template that lists all your posts in reverse chronological order. You can of course use different arguments for get_posts(). Refer to the Wordpress Codex to see how.

<?php
/**
 * Template Name: Archive Page
 *
 * @package WordPress
 * @subpackage My Theme
 */
include('header.php'); ?>
<body id="page">
	<?php include('nav.php'); ?>
	<section id="main" role="main" class="cf">
	<h1>Awesome Archive Page</h1>
	<ul class="post-list">
     <?php 
        // 1. store our loop preferences in an array
        $args = array('numberposts'     => 999, // notice this has to be "numberposts", not "posts_per_page"
       'order'           => 'DESC', // the other option is ASC
       'orderby'         => 'post_date', 
	   'post_type'       => 'post',
       'post_status'     => 'publish'
        );
        // 2. Run get_posts() on the $args array and store the result in $myposts  
        $myposts = get_posts( $args );
        // 3. Run a foreach loop on $myposts to access our content, combined with the annoying-but-necessary setup_postdata function.
        foreach( $myposts as $post ) :  setup_postdata($post); ?>    
      <?php include('snippet-post-link.php'); ?>
        <?php endforeach; ?>
        </ul>
<?php include('footer.php'); ?>