Fixing the pagination error using custom permalink structure in WordPress

Posted on 01/05/10, in WordPress, by kevin

For a while this has been really annoying me. Whenever I use the permalink structure /%category%/%postname%/ I get 404 errors when using the next_posts_link() and previous_posts_link(). I a fix for this here. You can use this code in a themes functions.php file or use it as a plugin.

/*
Plugin Name: Fix Paging in Category Listings
Plugin URI: http://www.thinkbarefoot.com
Description: Fixes a bug where next/previous links are broken in category by year/month listings
Version: 0.5
Author: Doug Smith
Author URI: http://www.thinkbarefoot.com

Copyright 2007  Doug Smith  (email: dsmith@thinkbarefoot.com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

*/

/**
 * Function to fix problem where next/previous buttons are broken on list
 * of posts in a category when the custom permalink string is:
 * /%category%/%year%/%monthnum%/%postname%/
 * The problem is that with a url like this:
 *
 * /category/2007/10/page/2
 *
 * the 'page' looks like a post name, not the keyword "page"
 */
function remove_page_from_query_string($query_string)
{
    if ($query_string['name'] == 'page' && isset($query_string['page'])) {
        unset($query_string['name']);
        // 'page' in the query_string looks like '/2', so split it out
        list($delim, $page_index) = split('/', $query_string['page']);
        $query_string['paged'] = $page_index;
    }
    return $query_string;
}

add_filter('request', 'remove_page_from_query_string');

Happy days.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Blogosphere News
  • DZone
  • email
  • LinkedIn
  • MySpace
  • PDF
  • RSS
  • StumbleUpon
  • Twitter

3 Responses to “Fixing the pagination error using custom permalink structure in WordPress”


Ziya Fortunato
2-4-2010

Great article. There’s a lot of good information here, though I did want to let you know something – I am running Redhat with the latest beta of Firefox, and the design of your blog is kind of quirky for me. I can read the articles, but the navigation doesn’t work so well.

Thanks a lot, this has been bugging me for a while now, and this fixes it so easily :)


Nazcain
5-10-2010

Thanks, man!

Leave a Reply