slash slash - 4 years ago 470
PHP Question

Wordpress category.php page pagination showing 404 page

In category.php page default posts are shown from certain category with pagination, and 'category' is removed in url from permalinks settings.

Unfortunately it redirects to 404 page while paginating to second page.

I even tried to check category pagination in wordpress default 2015 theme it wont work in there too.

Here is my category.php just with wordpress loop for testing.

if ( have_posts() ) :
while ( have_posts() ) : the_post();
the_title();
endwhile;
endif;

next_posts_link( 'Older posts' );
previous_posts_link( 'Newer posts' );


Note: everything works well if category is not removed from url.

http://www.domain.com/category/my_category/page/2 (works)
http://www.domain.com/my_category/page/2 (doesnt work)


Do i need to add/modify anything to make it work ?

Answer Source

This is normal, please try using code below:

add_filter( 'category_rewrite_rules', 'vipx_filter_category_rewrite_rules' );
function vipx_filter_category_rewrite_rules( $rules ) {
    $categories = get_categories( array( 'hide_empty' => false ) );

    if ( is_array( $categories ) && ! empty( $categories ) ) {
        $slugs = array();
        foreach ( $categories as $category ) {
            if ( is_object( $category ) && ! is_wp_error( $category ) ) {
                if ( 0 == $category->category_parent ) {
                    $slugs[] = $category->slug;
                } else {
                    $slugs[] = trim( get_category_parents( $category->term_id, false, '/', true ), '/' );
                }
            }
        }

        if ( ! empty( $slugs ) ) {
            $rules = array();

            foreach ( $slugs as $slug ) {
                $rules[ '(' . $slug . ')/feed/(feed|rdf|rss|rss2|atom)?/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
                $rules[ '(' . $slug . ')/(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
                $rules[ '(' . $slug . ')(/page/(\d)+/?)?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[3]';
            }
        }
    }
    return $rules;
}

Hope this will be helpful :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download