Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Pagination on custom wp_query in WordPress takes to 404 error page

Im have a loop with wp_query with the following code:

<?php
    $temp = $wp_query;
    $wp_query= null;
    $wp_query = new WP_Query();
    $wp_query->query("showposts=2&paged=$paged");
?>

<?php if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    <?php the_title() ?>
<?php endwhile; ?>
<?php else: ?>
    <article>
        <h2><?php _e( 'Sorry, nothing to display.', 'theme' ); ?></h2>
    </article>
<?php endif;  my_pagination(); wp_reset_query()?>

with standard pagination :

<?php 
function my_pagination()
{
    global $wp_query;
    $big = 999999999;
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'prev_text'    => __('<i class="fa fa-chevron-left"></i>'),
        'next_text'    => __('<i class="fa fa-chevron-right"></i>'),
        'total' => $wp_query->max_num_pages,
    ));
}
?>

The pagination is showing correctly on the page, but whenever I click on the pagination link it takes me to the error page.

Tried everything now and have no idea what can be the reason for it.

Amy help much apprecieated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Had a hard time with it too :) Was easier to search when I realized it's wrong calculated post per page number, and here is a magic trick: (to be added to functions.php)

function my_post_count_queries( $query ) {
  if (!is_admin() && $query->is_main_query()){
    if(is_home()){
       $query->set('posts_per_page', 1);
    }
  }
}
add_action( 'pre_get_posts', 'my_post_count_queries' );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...