I want to show posts from all categories on the archive.php page. The way I made it, just works inside a category page. For example, If I access "myurl/category/test-category/" the page works correctly, but it only shows posts from "test category". If I access "myurl/category/ it just returns a blank page.
My archive.php:
<?php get_header(); ?>
<div class="custom-container archive-wrapper">
<?php if(have_posts() ): while (have_posts() ): the_post(); ?>
<div class="blog-post-archive">
<div class="img-archive-wrapper d-xl-flex">
<img src="<?php echo wp_get_attachment_url(get_post_thumbnail_id( $post->ID ), 'medium' ); ?>" alt="Blog image" class="blog-image-archive">
<div class="blog-post-archive-infos">
<h2 class="archive-title"><?php the_title(); ?></h2>
<span class="post-date-archive"><?php echo get_the_date(); ?></span>
<p><?php the_excerpt( ) ?></p>
<a href="<?php the_permalink();?>" class="see-more-posts"> Ver mais</a>
</div>
</div>
</div>
<?php endwhile; else: endif; ?>
<div class="pagination__links">
<?php the_posts_pagination( ); ?>
</div>
</div>
<?php get_footer(); ?>
My Answer:
To show posts from all categories on the archive.php page in WordPress, you can modify the main query using pre_get_posts hook. Here's how you can do it:
1. Open your theme's functions.php file.
2. Add the following code:
php
function custom_archive_query( $query ) {
if ( $query->is_archive() && $query->is_main_query() ) {
$query->set( 'posts_per_page', -1 );
}
}
add_action( 'pre_get_posts', 'custom_archive_query' );
This code will modify the main query on archive pages to show all posts from all categories. The `posts_per_page` parameter is set to `-1` to display all posts.
After adding this code, save the functions.php file and refresh your archive.php page. Now, it should display posts from all categories.
Rate this post
3 of 5 based on 1083 votesComments