Reputation: 638
My archive page with added numeric pagination won't sort out the right category and instead shows posts from all the categories. Let's say the category is bananas (http://localhost/tkeblog/category/bananas/) and I get post from categories bananas, oranges and apples. Also the pagination system doesn't show posts with thumbail yet it works on my index.php page. What am I doing incorrectly to filter the posts by category?
<?php
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
query_posts(array(
'post_type' => 'post', // You can add a custom post type if you like
'paged' => $paged,
'posts_per_page' => 5
));
if ( have_posts() ) : the_post(); ?>
<div class="blogitem a">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part('catalog',get_post_format()); ?>
<?php endwhile; ?>
<div class="pagination">
<?php my_pagination(); ?>
</div>
</div>
<?php else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php wp_reset_query(); ?>
<?php endif; ?>
Upvotes: 1
Views: 191
Reputation: 5449
If we take a look at the default TwentyTwentyOne Wordpress theme archive.php
we can see that the archive template is just using a default loop to display all posts from all categories, not a custom query.
I believe this answers your question.
<?php
if( have_posts() ):
while( have_posts() ): the_post();
// ... template
endwhile;
else:
// ... fallback
endif; ?>
If you want to customize the default query output from the archive.php
page, the best practice is to do it from your function.php
page. You can use the the action hook filter pre_get_posts
.
Fires after the query variable object is created, but before the actual query is run. Be aware of the queries you are changing when using the pre_get_posts action. Make use of conditional tags to target the right query.
<?php
add_action( 'pre_get_posts', function ( $query ) {
if ( ! is_admin() && $query->is_archive() && $query->is_main_query() ) {
if ( get_query_var( 'post_type' ) == 'post' ) {
$query->set( 'post_type', array( 'post' ) );
$query->set( 'posts_per_page', 12 );
$query->set( 'orderby', array( 'date' ) );
$query->set( 'order', array( 'ASC' ) );
} else {
$query->set( 'posts_per_page', 6 );
$query->set( 'orderby', array( 'date' ) );
$query->set( 'order', array( 'ASC' ) );
};
};
}; ?>
Upvotes: 1