如何修改WordPress的archive.php仅显示各分类最新文章?
How to Modify archive.php to Show Only the Latest Post per Category
Got it, let's adjust your WordPress archive.php so it only displays the most recent post for each category. Here's a step-by-step fix tailored to your existing code:
The Problem with Your Current Code
Your current setup uses the default main query, which pulls all posts in the current category. The while loop then outputs each full post one after another—we need to tweak that query to only grab the latest single post.
Modified Code for archive.php
Replace your existing code with this updated version:
<?php get_header(); ?> <?php // Override the main query to fetch only the latest 1 post in the current category global $wp_query; $args = array_merge( $wp_query->query_vars, array( 'posts_per_page' => 1, 'orderby' => 'date', 'order' => 'DESC' ) ); $wp_query = new WP_Query( $args ); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php topfit_mikado_get_title(); ?> <?php get_template_part('slider'); ?> <div class="mkd-container"> <?php topfit_mikado_image_title_featured_image(); ?> <div class="mkd-container-inner"> <?php do_action('topfit_mikado_after_container_open'); ?> <?php topfit_mikado_get_blog_single(); ?> <!-- Keeps full post display as before --> <?php do_action('topfit_mikado_before_container_close'); ?> </div> <?php topfit_mikado_get_single_post_navigation_template(); ?> </div> <?php endwhile; ?> <?php else : ?> <!-- Fallback for empty categories --> <p><?php esc_html_e('No posts found in this category.', 'topfit'); ?></p> <?php endif; ?> <?php get_footer(); ?>
Key Changes Explained
- Query Adjustment: We're merging the existing category query parameters with new ones to limit results to 1 post, sorted by date (newest first). This ensures we only get the latest post for the current category, while keeping the category filter intact.
- Preserved Full Post Display: The
topfit_mikado_get_blog_single()function still outputs the full post content, just like your original code—so the styling and layout will match what you had before, but only for the latest post. - Empty Category Fallback: Added an
elseblock to show a friendly message if a category has no posts, which improves user experience.
Quick Tips
- Backup First: Always make a copy of the original
archive.phpbefore modifying it, just in case you need to revert. - Use a Child Theme: If your theme has a child theme, copy
archive.phpto the child theme directory and make changes there—this way, theme updates won't overwrite your customizations. - Adjust Later: If you ever want to show more than one post again, just change the
posts_per_pagevalue from1to your desired number.
内容的提问来源于stack exchange,提问作者Bakar
相关产品推荐
相关产品推荐

