【问题标题】:Custom WP_Query pagination shows 404 after page-2自定义 WP_Query 分页在第 2 页后显示 404
【发布时间】:2017-07-20 19:07:29
【问题描述】:

这是我的 index.php 循环:

<?php 
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'posts_per_page' => 3, 'paged' => $paged ) ); 
?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
      <article>
        <h3><?php the_title(); ?></h3>
      </article>
<?php endwhile; ?>

<?php if ( get_next_posts_link('Next', $query->max_num_pages)) : ?>
  <nav class="navigation paging-navigation" role="navigation">
    <?php echo get_next_posts_link( 'Next', $query->max_num_pages ); ?>
  </nav>
<?php endif; ?>

  <?php wp_reset_postdata(); ?>

<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

这很简单,但问题在于分页。在索引页面上,我有指向 page/2 的链接,当我单击它时,一切看起来都很好,但是当我在 page/2 上并单击链接 Next 进入 page/3 时,我收到 404 错误。
我做错了什么?

【问题讨论】:

标签: wordpress


【解决方案1】:

我找到了一个解决方案,对 index.php 来说并不难,但后来我注意到我的 tag.php 甚至没有显示 page/2,所以我在那里进行了一些更改以使其正常工作:

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

【讨论】:

    【解决方案2】:

    请尝试在functions.php中添加此代码并再次检查分页

    <?php
    if ( ! function_exists('my_pagination')) :
        function my_pagination() {
            global $wp_query;
    
            $big = 999999999; // need an unlikely integer
    
            echo paginate_links( array(
                'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                'format' => '?paged=%#%',
                'current' => max( 1, get_query_var('paged') ),
                'total' => $wp_query->max_num_pages
            ) );
        }
    endif;
    
    ?>
    

    并在重置后元之前添加此代码

     <div class="blog_pagination">
             <?php my_pagination(); ?>
      </div>
    

    希望这项工作

    【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2014-07-12
    • 2012-12-31
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2018-05-28
    • 2013-01-13
    相关资源
    最近更新 更多