How to link custom archive templates to different WordPress post types

3-minute read
2026-03-18
2026-06-04
1,998
I earn commissions when you shop through the links below, at no additional cost to you.

The hierarchical structure of WordPress theme templates is at the heart of its strength and flexibility. It allows developers to create unique display pages for different types of content by following specific file naming conventions. This mechanism is just as clear and effective for archive pages (i.e., pages that list articles). It is essential to understand and apply these conventions correctly. archive-{post_type}.php This naming convention is crucial for creating dedicated list pages for custom article types. This article will systematically explain the entire process, from the principles to the practical implementation, and finally to troubleshooting potential issues.

Understanding the template hierarchy and the archiving page mechanism

When a user visits a page that displays a list of articles, such as your blog homepage or a category page, WordPress initiates a process called the “main query” to retrieve the relevant articles. At the same time, it looks for the most suitable PHP template file to render the page based on the context of the current query, following a predefined hierarchy of priorities. This hierarchy is known as the “template hierarchy.”

For the archive page, the path used to locate it follows a specific pattern. Assuming the user is accessing the archive page for the default “Articles” type, WordPress will search in the following order:archive-post.php -> archive.php -> index.phpAs long as the first existing file is found, it will be used.

Recommended Reading Mastering WordPress Custom Post Types: A Comprehensive Practical Guide from Creation to Publication

The core of this mechanism lies in… archive-{post_type}.php…Here… {post_type} This is a variable that needs to be replaced with the registered name of the article type. For example, to create an archive page for a custom article type named “Project,” you will need a name that represents that article type. archive-project.php The file in question. WordPress will only fall back to the default/standard version if this file does not exist. archive.phpThis allows us to precisely control the way lists of different content types are displayed.

UltaHost WordPress Hosting
30-day refund guarantee, unlimited bandwidth and database usage, free DDoS protection; purchase for 3 years and get a discount of 50%.

Create a custom article type archive template.

Make sure that the article type supports the archiving feature.

The prerequisite for creating a template file is that your custom post type (CPT) must explicitly declare its support for archiving. This is usually specified when... register_post_type When registering a function for the CPT (Content Provider Type), it is done through parameter settings.

In the parameter array of the registration function,has_archive The parameter controls whether to enable the archive page. Set it to… true It is an essential step. If set to... false Or not set (default value is…) falseEven if you create the correct template file, WordPress will not generate the corresponding URL to access this archive page.

A standard example of a CPT (Claim Preparation Tool) registration that supports archiving is as follows:

function my_register_custom_post_type() {
    $labels = array(
        'name' => '产品',
        'singular_name' => '产品',
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true, // 启用存档功能
        'rewrite' => array('slug' => 'products'), // 可选:自定义存档页URL别名
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-cart',
    );
    register_post_type('product', $args);
}
add_action('init', 'my_register_custom_post_type');

Constructing the structure and content of a template file

After confirming that CPT supports archiving, the next step is to create the corresponding template files in the directory of your activity themes. The naming of these files must strictly follow the established conventions. archive-{post_type}.php The format should be consistent, and… {post_type} It must exactly match the name used during registration (case sensitive).

Recommended Reading From Scratch: A Comprehensive Guide to WordPress Theme Development and Best Practices

Within this file, you can use WordPress’s template tags and loops just like you would when creating other page templates. It provides a basic and complete framework for building your content. archive-product.php It might look like this:

<?php
/**
 * 模板名称:产品存档页
 * 用于展示“product”自定义文章类型的文章列表
 */
get_header(); ?>

<main id="primary" class="site-main">
    <header class="archive-header page-header">
        &lt;?php
            the_archive_title( &#039;<h1 class="archive-title page-title">', '</h1>' );
            the_archive_description( '<div class="archive-description">', '</div>' );
        ?&gt;
    </header>

<?php if ( have_posts() ) : ?>
        <div class="product-archive-wrapper">
            <?php
            while ( have_posts() ) :
                the_post();
                ?>
                <article id="post-<?php the_ID(); ?>" no numeric noise key 1012>
                    <a href="/en/</?php the_permalink(); ?>" class="product-thumbnail-link">
                        <?php if ( has_post_thumbnail() ) : ?>
                            <?php the_post_thumbnail('medium'); ?>
                        <?php endif; ?>
                    </a>
                    <div class="product-content">
                        <h2 class="product-title">
                            <a href="/en/</?php the_permalink(); ?>"></a>
                        </h2>
                        <div class="product-excerpt">
                            
                        </div>
                        <a href="/en/</?php the_permalink(); ?>" class="read-more-link">View Details</a>
                    </div>
                </article>
            
        </div>

2,
            'prev_text' =&gt; __( '上一页', 'textdomain' ),
            'next_text' =&gt; __( '下一页', 'textdomain' ),
        ) );
        ?&gt;
        <section class="no-products">
            <p>Sorry, no products were found at this time.</p>
        </section>
    
</main>

&lt;?php
get_sidebar();
get_footer();

Advanced Control and Customization Techniques

Using conditional logic in a generic archive template

Sometimes, you might want multiple different types of articles to share the same… archive.php The files are displayed, but different content is shown depending on their type. This is when WordPress’s Conditional Tags become extremely useful.

The most relevant condition is is_post_type_archive() Function. You can... archive.php Use it to customize titles, descriptions, or loop structures for different CPTs (Cost-Per-Transaction items).

hosting.com Shared Hosting
High performance with AMD EPYC CPUs, NVMe SSD storage and LiteSpeed, 24/7, 24x7 expert in-house support, advanced security measures including SSL, brute force, malware and DDoS protection, savings of up to 73%
// 在 archive.php 文件内
if ( is_post_type_archive('product') ) {
    echo '<h1>Our products and solutions</h1>';
    get_template_part('template-parts/loop', 'product-grid');
} elseif ( is_post_type_archive('event') ) {
    echo '<h1>Recent Events and Seminars</h1>';
    get_template_part('template-parts/loop', 'event-list');
} else {
    // 默认的文章存档(博客)
    echo '<h1>Blogs and News</h1>';
    get_template_part('template-parts/loop', 'default');
}

Use hooks to modify the archive page query.

Directly modifying the loops in the template files will only change the output style. If you want to change the logic behind how the archive page retrieves articles—such as adjusting the number of articles per page, the sorting method, or filtering certain articles—you must use other methods. pre_get_posts Action hooks. This is the recommended approach by WordPress, as it ensures proper functionality when working with features such as pagination.

The following code example demonstrates how to modify the main query for the “Product” archive page to sort the items by a custom field and display 9 items per page:

function customize_product_archive_query($query) {
    // 确保只在非管理后台、主查询、且是产品存档页时生效
    if ( ! is_admin() && $query->is_main_query() && is_post_type_archive('product') ) {
        $query->set('posts_per_page', 9); // 每页9个产品
        $query->set('orderby', 'meta_value_num'); // 按数字元字段排序
        $query->set('meta_key', 'product_price'); // 指定元字段键
        $query->set('order', 'ASC'); // 升序排列
    }
}
add_action('pre_get_posts', 'customize_product_archive_query');

Important Note: Avoid using this in template files at all costs. query_posts() Modifying the main query can cause issues such as query object corruption, pagination errors, and compatibility problems with plugins.

Recommended Reading The Complete Guide to WooCommerce E-commerce Website Development: From Setup to Advanced Feature Implementation

Dynamically loading different template files

For more complex scenarios, you can use… template_include The filter dynamically determines which template file to load. This allows you to switch templates based on any criteria, such as user role, URL parameters, time, etc.

For example, the archive page for “Products” loads a different template under certain conditions:

InterServer Shared Hosting
Shared hosting $2.50 USD per month , first month $0.1 USD promo code tryinterserver, 461 cloud apps scripts, one click install.
function load_special_product_archive_template($template) {
    if ( is_post_type_archive('product') && some_custom_condition() ) {
        $new_template = locate_template('archive-product-special.php');
        if ( ! empty($new_template) ) {
            return $new_template;
        }
    }
    return $template;
}
add_filter('template_include', 'load_special_product_archive_template');

Troubleshooting and Best Practices

Even if all steps are followed, the archive template may still not function as expected. Here is a systematic list of troubleshooting items to consider:

1. Refresh the fixed links: This is the most common and important step. Go to the WordPress backend, navigate to “Settings” -> “Fixed Links”, and then click “Save Changes”. This action will refresh WordPress’s rewrite rules, making the new archive page URL rules take effect.
2. Verify CPT registration: Ensure that the code used for CPT registration is being executed correctly, and… has_archive The parameters are finally passed on to... register_post_type Indeed, time is... trueCheck to see if any other plugins or theme code have overridden your CPT (Custom Post Type) settings.
3. Check the file location and naming: Please confirm. archive-{post_type}.php The file is located in the root directory of the correct theme. Please check the file name for spelling, including case sensitivity, to ensure it matches the registered name of the post_type exactly.
4. Handling theme overrides: If you are using sub-templates, make sure that the parent theme does not have a template file with the same name that would override the sub-template’s template hierarchy. Additionally, check for any other potential issues that could affect the theme’s functionality. template_include Filter interference.
5. Cache Issues: Clear all levels of cache, including the WordPress object cache, page caching plugins, as well as server or CDN caches.

Regarding best practices, it is recommended to always use them. pre_get_posts rather than query_posts Come and modify the query; use it in the template file. post_class() Generate dynamic CSS classes for the article to facilitate style design; also add clear comments in the header of your custom template files.

summarize

Linking custom archive templates to different article types in WordPress is a process of precisely matching the content with its visual presentation. The key to this lies in understanding and effectively utilizing these templates. archive-{post_type}.php These template hierarchy rules cover everything from ensuring that the archiving function is enabled during CPT registration, to correctly creating and naming template files, and finally to how to use them. pre_get_posts Using hooks for advanced query control is crucial at every step of the process. Once you master these skills, you will be able to easily create list pages for each type of content on your website that are both functional and uniquely styled, thereby significantly enhancing the professionalism of the website and the user experience.

FAQ Frequently Asked Questions

What does the URL for a custom archive page look like?

By default, WordPress generates the URL for archive pages based on the name you use when registering a custom post type. For example, a post type named… product The CPT (Claim Preparation Tool) URL for its archive page is usually… 你的网站域名/product/You can do this by setting the relevant options during the registration process. rewrite in the parameters slug The option allows you to customize this URL alias.

Can I display the filtering of articles based on a custom taxonomy in the archive template?

Certainly. This is a common requirement for archive pages. You can… archive-{post_type}.php The template uses get_terms() The function retrieves all the terms associated with a custom taxonomy (such as “Product Category”) and then displays them as filter links in a loop. When a user clicks on one of these category links, they are directed to the archive page for that taxonomy. At that point, WordPress will search for and load the relevant content. taxonomy-{taxonomy_name}.php Or taxonomy-{taxonomy_name}-{term_slug}.php Waiting for templates…

How to create a list page for article types that do not have the archiving feature enabled?

If a certain type of article… has_archive Set it to falseIn that case, you won't be able to access the list using the standard archive URL. An alternative is to create a regular page (Page) and then use that page template to display the content. WP_Query Or get_posts() This function is used to retrieve and display articles of a specific type. You can assign a custom template to this page and include dedicated query and loop code within it.

Pagination does not work on the custom archive pages. How can this be fixed?

Pagination failures almost always occur due to incorrect modifications of the Main Query. Please make sure that you are not using any modified versions of the Main Query in your templates. query_posts()If you need to modify the query parameters (such as the number of articles or the sorting order), you must use… pre_get_posts Hooks, as described in this article. Also, make sure to use them when making the calls. the_posts_pagination() When implementing a pagination function, it operates on a global scope (i.e., it affects all instances or contexts where the function is used). $wp_query An object, rather than a custom one. WP_Query Example.