Nearly everyone has pagination issues with custom queries (including get_posts()
) on templates on their initial foray into subject. This is compounded with a lot of bad examples on the internets. The issues introduced are not readily apparent.
The only pagination function that really works with custom queries is paginate_links()
. All other functions assume you want to paginate the requested page and not the queried posts.
Even with paginate_links()
, you still run into trouble by trying to use the “paged” query var. It rightly belongs to the main query and not your custom query. Trying to usurp it for your own means does not work very well. IMO you’re better off introducing your own pagination query var to avoid any confusion and cross talk between queries.
Better yet, don’t do custom queries on a template if those results are going to be the only queried content on the page. Instead, alter the main query through the “pre_get_posts” action so it returns the results your custom query would have returned. Then there’s no need for another query, and WP handles pagination for you. Then most pagination functions will work as intended and you don’t have to use paginate_links()
, though it would still work.
Thanx a lot “bcworkz”…You gave me the way to go: pre_get_posts was finally the thing to get it to work perfect.
My solution now is the function:
function numberposts_for_index( $query ) {
if( $query->is_main_query() && ! is_admin() && $query->is_home() ) {
$query->set( 'posts_per_page', '4' );
$query->set('post_status','future,publish');
}}
add_action( 'pre_get_posts', 'numberposts_for_index' );
and my code in the index.php:
<?php
if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
else { $paged = 1; }
$data= new WP_Query(array(
'post_type'=>'post',
'posts_per_page' => 4,
'post_status' => 'future, publish',
'paged' => $paged,
));
if($data->have_posts()) :
while($data->have_posts()) : $data->the_post();?>
<?php the_content('<br />→ weiterlesen …'); ?>
<?php endwhile; ?>
<div><?php the_posts_pagination( array(
'mid_size' => 4,
'prev_text' => __( '?', 'neuere Beiträge' ),
'next_text' => __( '?', 'ältere Beiträge' ),
) ); ?></div><p> </p>
<?php else :?>
<h3><?php _e('404 Error: Not Found', ''); ?></h3>
<?php endif; ?>
<?php wp_reset_postdata();?>
sorry….the code I wrote above for the index.php is a bit too much. Forgot to clean up.
There is no need for the Query anymore…pre_get_post function does the work:
So this is the correction vor the index:
<?php
if(have_posts()) :
while(have_posts()) : the_post();?>
<?php the_content('<br />→ weiterlesen …'); ?>
<?php endwhile; ?>
<div><?php the_posts_pagination( array(
'mid_size' => 4,
'prev_text' => __( '←', 'neuere Beiträge' ),
'next_text' => __( '→', 'ältere Beiträge' ),
) ); ?></div><p> </p>
<?php else :?>
<h3><?php _e('404 Error: Not Found', ''); ?></h3>
<?php endif; ?>
<?php wp_reset_postdata();?>