To create an archive page and a single post page for a custom post type in WordPress, follow these steps:
1. Create the Custom Post Type
If you haven’t already created your custom post type, you can register it in your theme’s functions.php file or via a plugin like Custom Post Type UI.
2. Create the Archive Page Template
WordPress will automatically look for a template file with the name archive-{post-type}.php
for the archive page of your custom post type.
Suppose your custom post type is named portfolio. In this case, create a file named archive-portfolio.php
.
Place this file in your theme folder, e.g., /wp-content/themes/your-theme/archive-portfolio.php.
Basic Structure for archive-portfolio.php
:
<?php get_header(); if ( have_posts() ) : echo '<h1>' . post_type_archive_title() . '</h1>'; echo '<div class="portfolio-archive">'; while ( have_posts() ) : the_post(); ?> <div class="portfolio-item"> <a href="<?php the_permalink(); ?>"> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> </a> </div> <?php endwhile; echo '</div>'; the_posts_navigation(); else : echo '<p>No posts found.</p>'; endif; get_footer();
This template will display all posts for the portfolio post type, including each post’s title, excerpt, and link to the single post page.
You can style this with CSS as needed by adding custom classes.
3. Create the Single Post Page Template
For the single post view, WordPress will look for a template file named single-{post-type}.php
.
For our example portfolio post type, create a file named single-portfolio.php.
Place it in your theme folder: ../wp-content/themes/your-theme/single-portfolio.php
.
Basic Structure for single-portfolio.php
:
<?php get_header(); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="portfolio-single"> <h1><?php the_title(); ?></h1> <div class="portfolio-content"> <?php the_content(); ?> </div> <?php if ( has_post_thumbnail() ) : ?> <div class="portfolio-thumbnail"> <?php the_post_thumbnail('large'); ?> </div> <?php endif; ?> </div> <?php endwhile; else : echo '<p>No post found.</p>'; endif; get_footer();
This template displays the full content of a single portfolio post, along with the featured image if it’s set.
You can style this with CSS as needed by adding custom classes.