I've been trying to fix my pagination on for category pages but am at a loss. This is my pre_get_posts function for category pages.
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() // Only target the front end queries
&& $q->is_main_query() // Targets the main query only
&& $q->is_category() // Only target category pages
) {
$today = date( 'Y-m-d' );
$q->set( 'post_type', array( 'research_article', 'events' ) );
$q->set( 'posts_per_page', 12 );
$q->set( 'orderby', 'meta_value_num date' );
$q->set( 'meta_query', array(
array(
'key' => 'wpcf-date_time',
'value' => $today,
'compare' => '>=',
'type' => 'DATE',
),
array(
'key' => 'wpcf-date_time',
'compare' => 'NOT EXISTS'
),
'relation' => 'OR',
) );
}
});
Everything runs correctly EXCEPT it doesn't display 12 posts per page or include the pagination. I've tried including the_posts_pagination() on my category.php with no luck. Am I supposed to set a paged variable in this pre_get_posts function? If so, how?
My category.php code:
<?php get_header(); ?>
<div class="welcome">
<h1><?php echo single_cat_title(); ?></h1>
<?php echo category_description(); ?>
</div>
<div class="site">
<main id="primary" class="site-main two-col-index">
<?php // Output custom query loop
if ( have_posts() ) :
$i = 0;
while ( have_posts() ) :
the_post();
if ( $i == 0 ) : ?>
<div class="post-box">
....
</div> <!-- closes the first div box -->
<?php else: ?>
<?php get_template_part( 'template-parts/content', 'post_box' ); ?>
<?php endif; $i++; ?>
<?php
endwhile;
endif;
the_posts_pagination();
?>
</main><!-- #main -->
</div>
<?php get_footer(); ?>
WP_Query
orquery_posts
on yourcategory.php
template? Or is it a standard post loop? There's no code forcategory.php
so it's not possible to tellcategory.php
template, only thing I can think of is that you didn't get multiple pages of results.the_posts_pagination
only has output when there are multiple pages. You do not and should not addpaged
values in`pre_get_posts
, pagination parameters are imo a dead end and not the solution/cause of your issue. However, you can test this by settingposts_per_page
to 1 or 2$q->set( 'posts_per_page', 12 )
from my code and the pagination is working as expected! Perhaps there was some issue between my Settings for Posts and the posts_per_page definition for category.php