When you create a custom post type in WordPress, you often want a special archive page to display all posts of that type. WordPress lets you create a custom archive template file to control how this archive looks.
Step 1: Register Your Custom Post Type
First, you create a custom post type (CPT) in your theme’s functions.php
or via a plugin like CPT UI. Here’s a quick example registering a CPT called book
:
phpCopyEditfunction create_book_post_type() {
register_post_type('book', array(
'labels' => array(
'name' => __('Books'),
'singular_name' => __('Book'),
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'books'),
'supports' => array('title', 'editor', 'thumbnail'),
));
}
add_action('init', 'create_book_post_type');
Make sure 'has_archive' => true
is set to enable archive pages.
Step 2: Create the Custom Archive Template File
WordPress uses the template hierarchy to decide which template to load. For a CPT archive, it looks for a file named:
CopyEditarchive-{post_type}.php
For our example CPT book
, create a file named:
CopyEditarchive-book.php
Place this file in your active theme’s folder.
Step 3: Build the Template Structure
Here’s a basic example of archive-book.php
:
phpCopyEdit<?php get_header(); ?>
<div class="archive-books">
<h1>All Books</h1>
<?php if (have_posts()) : ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<p><?php the_excerpt(); ?></p>
</li>
<?php endwhile; ?>
</ul>
<?php
// Pagination
the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
));
?>
<?php else : ?>
<p>No books found.</p>
<?php endif; ?>
</div>
<?php get_footer(); ?>
This template shows a list of your custom post type posts with titles linking to single posts, excerpts, and pagination.
Step 4: Refresh Permalinks
After adding your CPT and archive template, go to Settings > Permalinks in your WordPress admin and click Save Changes to flush rewrite rules. This ensures your archive URLs work properly.