I am creating a category-{slug}.php
page for a specific category. This page has pagination also. This code successfully worked when calling the first page of the category page, but the problem starts when I clicked the pagination link.
When I clicked the "older entries" in the pagination, the URL changed to the following, but it\'s loading with index.php
instead of category-{slug}.php
and unable to show the post list:
http://localhost:90/wordpress/category/news/page/2/
The following URL is loading the category-news.php
successfully:
http://localhost:90/wordpress/category/news/page/1/
My code of the page category-news.php
is as follows...
get_header();
wp_reset_query(); ?>
<div class="pagewrap post-page-article">
<?php $count = 0;
//Added
$paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
global $query_string;
query_posts( $query_string . \'&posts_per_page=2&paged=\' . $paged );
//--End of addition
while ( have_posts() ) : the_post();
$this_page_img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'full\', false );
$this_page_img = $this_page_img[0];
$this_page_title = get_the_short_title();
$this_page_brief = get_the_short_excerpt( 200 );
$this_page_url = get_the_permalink();
?><div class="wide-colum-3">
<div class="image-side-block">
<img src="<?php echo $this_page_img; ?>" alt="<?php echo $this_page_title; ?>">
</div>
<h3><a href="<?php echo $this_page_url; ?>"><?php echo $this_page_title; ?></a></h3>
<p><?php echo $this_page_brief; ?></p>
<div class="clear-fix"></div>
<hr class="green-bar">
</div>
<?php endwhile;
// next_posts_link() usage with max_num_pages
next_posts_link( \'Older Entries\', $query->max_num_pages );
previous_posts_link( \'Newer Entries\' );
wp_reset_postdata(); ?>
<div class="clear-fix"> </div>
</div>
<?php get_footer();
最合适的回答,由SO网友:Pieter Goosen 整理而成
根据请求,自定义模板并不意味着自定义查询:-)。
如前所述,NEVER 使用query_posts
, 它破坏了主要的查询对象和页面功能,其中之一就是分页。许多插件和函数依赖于主查询对象,你打破了它,你也打破了那些函数。
由于这是一个自定义类别模板,因此根本不需要运行自定义查询来完成您想要完成的任务。主查询可以是safely 更改为pre_get_posts
在执行主查询以获得所需结果之前,对指定模板执行。
您可以在functions.php
, 这将为您的自定义类别模板提供每页2篇帖子and 它将正确处理分页问题;-)
add_action( \'pre_get_posts\', function ( $q )
{
if ( !is_admin() // Only targets front end
&& $q->is_main_query() // Targets only the main query
&& $q->is_category( \'SPECIAL CATEGORY\' ) // Only targets your custom category page, change accordingly
) {
$q->set( \'posts_per_page\', 2 ); // Sets 2 posts per page on special category page
}
});