WordPress Archive Page with Transients

I recently discovered transients, a caching method that you can use to save queries in the database or object cache (if used). It can save a lot of time to gather the information for a page to load and it can descrease the amount of load on your database / PHP.

I use two files for this short tutorial. This code is used on the archive page for www.maartenvandekamp.nl/archief/. It’s generated once and only changed when a post is saved. This way, it’s only regenerated when needed.

$posts = all_posts_archive_page();
if( $posts->have_posts() ) : while ($posts->have_posts() ) : $posts->the_post();
printf('<li>%1$s &mdash; <a href="%2$s" title="%3$s">%4$s</a></li>',
esc_html( get_the_date( get_option( 'date_format' ) ) ),
esc_url( get_permalink() ),
esc_attr( the_title_attribute( 'echo=0' ) ),
endwhile; endif; wp_reset_query(); ?>

I copied the template from an existing page and instead of showing the_content(). I pasted this code and saved the template. I called it template-archive.php.

You may have noticed, I fill the variable $posts with the function all_posts_archive_page();. This function is located in the file functions.php, which comes with every theme used by WordPress.

This is the code that retrieves the posts from the database and stores them in the database or object cache (if used):

function all_posts_archive_page() {
if ( false === ( $all_posts_for_archive = get_transient( 'all_posts_for_archive' ) ) ) {
$query = array( 'nopaging' => true );
$all_posts_for_archive = new WP_Query($query);
// transient set to last forever until another post is saved - all_posts_archive_page_transient_flusher takes care of the flush
set_transient( 'all_posts_for_archive', $all_posts_for_archive );
// do normal loop stuff
return $all_posts_for_archive;
 * Flush out the transients used in all_posts_archive_page()
function all_posts_archive_page_transient_flusher() {
delete_transient( 'all_posts_for_archive' );
add_action( 'save_post', 'all_posts_archive_page_transient_flusher' );

The second function (all_posts_archive_page_transient_flusher()) deletes the transient when a new post is saved, so when a post is edited or published, the cache will become expired and will be rebuild when a visitor visits the archive page again.