Daniil Nagikh
Daniil Nagikh

Reputation: 33

Pagination on category.php not working in wordpress

I use custom permalinks /%category%/%postname%/ On a category's page (category.php) I use pagination, for example, /shops/paged/2 and get 404 error

P.S. If I go to /shops/paged/1 it works P.P.S Use custom query WP_Query and wp_pagenavi()

global $paged;
if (get_query_var( 'paged' ))
    $my_page = get_query_var( 'paged' );
else {
    if( get_query_var( 'page' ) )
        $my_page = get_query_var( 'page' );
    else
        $my_page = 1;
    set_query_var( 'paged', $my_page );
    $paged = $my_page;
}
$args = array(array('posts_per_page'   => 2, 'paged'            => $paged, 'post_type' => 'post', 'category_name'    => 'my_category_nicename'));

$the_query = new WP_Query( $args );

...

while ( $the_query->have_posts() ):

...

How can I fix it?

Thank you very much!!

Upvotes: 2

Views: 6099

Answers (1)

Nathan Dawson
Nathan Dawson

Reputation: 19308

You need to modify the main loop on your category page instead of breaking out a new loop. The main loop of the category you're in doesn't have a page 2 so it never shows the category.php file that you modified, instead the 404 template is loaded.

In the example below I use pre_get_posts to check if we're on a category page and change the number of posts per page to 2.

function wpse_modify_category_query( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( $query->is_category() ) {
            $query->set( 'posts_per_page', 2 );
        } 
    } 
}
add_action( 'pre_get_posts', 'wpse_modify_category_query' );

Upvotes: 10

Related Questions