Show only single category posts on WordPress archive page

To display only a single category’s posts on a WordPress archive page, you can modify your theme’s functions.php file or create a custom template. The best approach is to use the pre_get_posts hook, which allows you to filter the query before WordPress retrieves posts. Here’s an optimized way to do it:

function filter_archive_by_category( $query ) {
if ( !is_admin() && $query->is_archive() && $query->is_main_query() ) {
$query->set( 'cat', 12 ); // Replace 12 with your category ID
}
}
add_action( 'pre_get_posts', 'filter_archive_by_category' );

This snippet ensures that only posts from a specific category appear on archive pages while maintaining performance and compatibility. You can replace the category ID (12) with the desired category’s ID, which can be found in the WordPress admin panel under Posts > Categories. This method is ideal for keeping your theme lightweight and SEO-friendly without modifying core files.