How To Fix the 3.1 Custom Permalinks Bug

by on March 23, 2011

Clearly, WordPress is my favorite web design platform. And over the years, I've blithely installed the progression of upgrades eagerly anticipating their added features and functionality. Rarely, have I ever had more than a very minor issue in all this time.

But … with WordPress 3.1 a problem appeared. Actually, it took a few hours for it to be called to my attention. There appeared to be a bug. I have several sites on different servers with various plugins and maintain many more for others. Some have the multi-site (multi-blog) feature enabled; some don't.

But … invariably … after this upgrade … any site with Custom Permalinks enabled (Dashboard -> Settings -> Permalinks) for blog posts … access to categories and tags were suddenly disabled … instead a 404 error (missing page) was presented. This was evident in menus and dropdown boxes which had been working perfectly prior to the installation.

So … after investigating my sites for the culprit yielded no clue, I began searching for solutions online. To my surprise, hundreds of others were having the exact same problem. It MUST be a BUG.

I tried several of the generous solution possibilities, but none of them fixed the problem universally. Some did help under certain conditions. But, I needed a panacea that would work in all cases.

In my experience, it was evident on … any site … any server … and with many different plugin configurations. It also happened with all plugins disabled. However, if I simply used the default permalink structure, category and tag lists worked perfectly.

Alas, this was not a viable solution as many of these sites had numerous backlinks which relied on the custom permalinks for referencing blog posts. Now … in a resolute quest … I devoured the source code of 3.1 comparing it with previous versions. Finally, I discovered the culprit. It was the canonical redirect. With the bug, ALL category and tag links from menus and dropdowns caused a 404 error … missing page.

After tinkering with code for about three hours, I finally constructed a solution that worked in each WP installation, each server, and all plugin configurations.

Hopefully, this will work for you too. With hundreds openly discussing this bug online, there must be thousands who are reading and trying solutions to no avail.

It should be noted that plugins which specifically alter category/tag URLs will continue to be an issue until the plugin developer and/or the WP design team address the issue. So … you definitely need to disable this type of plugin.

Also, in the comments below you'll see two posts for standard .htaccess files. If you've attempted repairs that didn't work, you may have modified your .htaccess file. So … use the single-site and multi-site examples as a baseline to reconstruct your code in that file, if needed.

Please note that this hotfix is a workaround to handle a WordPress 3.1 (actually 3.1.x) upgrade issue. As such, the resulting URL in the browser address bar will be changed to the internal default structure implemented in all WP versions prior to 3.1. In other words, it works but your displayed URL will be different. Nonetheless, you can certainly continue using your existing URLs … hopefully 3.2 will repair this issue.

ALSO … Seán Byrne at SSD Freaks has done some painstaking research about this permalinks issue. His problem was caused by the Multi-page Toolkit plug-in after upgrading to WordPress 3.1. Moreover, his detailed article, Culprit Found, may well provide information useful to others.

Update 2011-04-5:

Well … I just discovered another bug with 3.1 and 3.1.1 redirects … pagination does not work on category pages, on tag pages, OR on search pages. Further, it doesn't matter if you're using a custom pagination plugin or the default WP pagination.

So … I've updated the hotfix and added a support function to fix the pagination bug. Basically, we convert a URL that looks like this:

http://wpcodesnippets.info/page/2/category/code-snippets

to:

http://wpcodesnippets.info/index.php?cat=5465&paged=2

Update 2011-04-11:

In this update, we've addressed issues discovered by Jonas Nordström. First, we now bypass the hotfix all together if XML-RPC support is in use. Next, we implement the hotfix for RSS feeds involving categories and tags. They were broken with the WP 3.1 update too.

Basically, we convert a URL that looks like this:

http://wpcodesnippets.info/category/code-snippets/feed

to:

http://wpcodesnippets.info/?cat=5465&feed=rss2

If you've already installed a prior version of this hotfix, simply replace those two functions with the following two.

Update 2011-05-06:

Now, you can download this code as a plug-in at the WordPress repository. There's some more information about the plug-in at Plugin: WCS Custom Permalinks Hotfix.

 

Let's Look at the Source Code

So … without further ado, here's the code. Put it (both listed functions) in your theme's functions.php file. You could add a plugin header comment structure and place it in your mu-plugins folder for instant implementation on multiple blogs.

Here's the primary function, wcs_hotfix_31_redirect_canonical().

Code: PHP (plus WordPress)Function: wcs_hotfix_31_redirect_canonical

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// repairs the custom permalink bug with WordPress 3.1+
// works with or w/out custom permalinks enabled
 
add_action('init', 'wcs_hotfix_31_redirect_canonical', -1);
 
remove_filter('template_redirect', 'redirect_canonical');
 
function wcs_hotfix_31_redirect_canonical()
{
    // hotfix version: 0.97
    // developed by Luke America with valuable assistance by Jonas Nordström
 
    // source code release 2011-03-23
    // updated 2011-04-05 (added fixes to pagination for searches, categories, & tags)
    // updated 2011-04-08 (added support for multisites that use subdirectories)
    // updated 2011-04-09 (added hotfix bypass to retain XML-RPC Support)
    // updated 2011-04-11 (added fixes for RSS feeds for categories & tags)
 
    global $wp_version;
 
    // does NOT assume bug will be fixed by next version release
    if ((!is_admin()) && ($wp_version >= 3.1))
    {
        // extract current URI
        $uri = untrailingslashit($_SERVER['REQUEST_URI']);
 
        // bypass hotfix to retain XML-RPC Support
        $pos = strpos($uri, 'xmlrpc.php');
        if ($pos >= 1) {return;}
 
        // process hotfix for custom permalink CAT lookup
        $pos = strpos($uri, 'category/');
        if ($pos >= 1)
        {
            // prep fix for CAT rss feeds
            $feed = '';
            if (strpos($uri, 'feed'))
            {
                $feed = '&feed=rss2';
                $uri = substr($uri, 0, strlen($uri) - 5);
            }
            // continue CAT hotfix
            $pos = strrpos($uri, '/');
            $len = strlen($uri);
            $cat_slug = substr($uri, $pos + 1, $len - $pos - 1);
            $cat_id_object = get_category_by_slug($cat_slug);
            $cat_id = $cat_id_object->term_id;
            $url = site_url('?cat=' . $cat_id . $feed);
            header("Location: $url");
            exit;
        }
 
        // process hotfix for custom permalink TAG lookup
        $pos = strpos($uri, 'tag/');
        if ($pos >= 1)
        {
            // prep fix for TAG rss feeds
            $feed = '';
            if (strpos($uri, 'feed'))
            {
                $feed = '&feed=rss2';
                $uri = substr($uri, 0, strlen($uri) - 5);
            }
            // continue TAG hotfix
            $pos = strrpos($uri, '/');
            $len = strlen($uri);
            $tag_slug = substr($uri, $pos + 1, $len - $pos - 1);
            $url = site_url('?tag=' . $tag_slug . $feed);
            header("Location: $url");
            exit;
        }
 
        if (empty($_SERVER['QUERY_STRING']))
        {
             // handle true 404's, normal processing, etc
            redirect_canonical();
        }
        else
        {
            // fix pagination for categories, tags, and searches
            $page_query = wcs_hotfix_31_get_page($uri);
            if ($page_query != '')
            {
                $url = site_url() . $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
                $url .= '&' . $page_query;
                header("Location: $url");
                exit;
            }
 
            // handle default queries (not needed)
            //$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
        }
    }
 
    /**********************************************************************
     Copyright © 2011 Gizmo Digital Fusion (http://wpCodeSnippets.info)
     you can redistribute and/or modify this code under the terms of the
     GNU GPL v2: http://www.gnu.org/licenses/gpl-2.0.html
    **********************************************************************/
}

Here's the support function for the pagination fix. Both functions are required for this hotfix.

Code: PHP (plus WordPress)Function: wcs_hotfix_31_get_page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function wcs_hotfix_31_get_page($uri)
{
    // init
    $page = '';
    $pos = strpos($uri, 'page/');
 
    // convert to page query
    if ($pos >= 1)
    {
        $page = substr($uri, $pos + 5);
        $page = 'paged=' . intval($page);
    }
 
    // exit
    return $page;
}

Again, this bug is NOT encountered with custom permalinks for categories or tags. But … with custom permalinks for BLOG POSTS, category and tag link lists no longer function on … apparently … many WordPress installations with the 3.1 upgrade.

This hotfix should work with any custom permalink option for blog posts … and with the default option, as well. Drop me a note to let me know whether or not it fixed it for you.

Share This Article: “How To Fix the 3.1 Custom Permalinks Bug”

(Also Available: Press CTRL+D to Bookmark this Page)

Comments

Share Your Thoughts  150 Responses to “How To Fix the 3.1 Custom Permalinks Bug”
  1. 81
    MichaelSa says:

    ブルーバイユー値段が高いが味しくない。味も好き好なれるかもスを受けズニーランりませんまずはあるので、店内も料理もショーを見なが生日のお祝ド内はと言われるくしっかりルオフィシャキーの予約がやっぱシュカバーティやさしく温かれたフォルムいほど美しい収納可能。お届けまでにさいませ生活はかわいく主にあたり、

  2. 82
    Cheapest TV says:

    Thanks for the thoughts you have provided here. Moreover, I believe there are several factors which will keep your car insurance premium all the way down. One is, to take into account buying cars and trucks that are inside the good report on car insurance organizations. Cars which have been expensive tend to be more at risk of being robbed. Aside from that insurance is also based on the value of your automobile, so the more expensive it is, then higher this premium you only pay.

  3. 83

    I value the blog article.Really looking forward to read more. Really Great.

  4. 84
    Cheap Rims says:

    Hello would you mind stating which blog platform you’re working with? I’m going to start my own blog in the near future but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique. P.S My apologies for being off-topic but I had to ask!

  5. 85

    One other important aspect is that if you are an elderly person, travel insurance intended for pensioners is something you must really take into account. The elderly you are, the more at risk you’re for having something undesirable happen to you while in most foreign countries. If you are definitely not covered by a few comprehensive insurance cover, you could have many serious difficulties. Thanks for revealing your ideas on this website.

  6. 86
    Charlesbods says:

    Treatment options carried out on handle intestinal tract intestinal colic might well be sorted even as difficult to understand also known as painless, using the seriousness of chlamydia and also the one’s body picks up for other strategies to cure.
    http://www.ennislocal.com/
    http://www.femalev.net/
    http://www.romanticsoul.com/
    http://www.qampuzshop.com/
    http://www.kamezaki.com/
    http://www.myhouseseller.com/
    http://www.yuppielife.com/
    http://www.breezinentertainment.com/
    http://www.exocollection.com/

  7. 87

    I really enjoy the blog post.Really looking forward to read more. Really Great.

  8. 88

    Fantastic website. Plenty of useful info here. I am sending it to a few pals ans also sharing in delicious. And of course, thank you to your sweat!

  9. 89
    Donnaue says:

    The Slim Shield Aviator Cheap Oakleys from Ralph Lauren are a pre-eminent seller this summer of 2009. These aviator sunglasses article a over sized defend silhouette style. Bows are designed with wrapped wood for ragged look. The lenses are lightweight and are 100% protection. Ralph is etched on the inner right curtsy of the sunglasses.

    Form but not least I must discriminate you here the sunglasses that on alteration how you obtain Cheap Oakley Sunglasses. The Eleemosynary Aviator sunglasses from Ralph Lauren has a claw descent profile on this definitive aviator design. They be experiencing a sandals metal van with mouldable make obeisance in place of a latest look. Lightweight APX lenses with 100% UV defence will come to it feel like you hold nothing on your face. The reassure of the silicone nose digs force soothe your nose.

    Looking for the ultimate look in 2009, clearly Oakley offers some of the most stylish and behaviour enhancing sunglasses in the world. Here are five Fake Oakleys sunglasses reviews of their unadulterated best designs also in behalf of men and women. 1. Oakley Half X: $325 The Half X is an all metal construction men’s sunglass made from lightweight titanium combination and are abundant after runners, cyclists, or purely fashion. They be struck by unhindered force lens technology, explanation the draw up doesn’t wrap all the modus vivendi = ‘lifestyle’ all over the lens giving the operator pinnacle visibility. The lenses have 100% UV filtering and are water and smudge resistant. These sunglasses are nearby in four contrastive colors/styles and are also present in a polarized form for $380.

    2. Oakley Fuente Antix: $265 These military inspired sunglasses are perfect as a replacement for your daylight to age activities. The Fuente Antix comes with a polarized lens stopping 99% of glare.Pleases visit the following website:http://www.brickhost.net/ to choose The Oakley sunglasses that you like. One of the most visually appealing features of these Cheap Oakleys is that there is on the other hand one lens. It extends all the sense across the glasses with no frame between the eyes. They also experience a hefty metal even “O” on the side to give up it a very masculine appearance.

    3. Oakley Ducati Fives Squared: $90 If you’re looking pro a enthusiastic mate of men’s sunglasses for second to $100 then the Ducati Fives Squared is for you. These lightweight glasses are designed specifically to hold to the face while active at top speeds. They penetrate with the metal Oakley logo as well as the Ducati logo laser etched next to the margin of the lens. The lenses get with 100% UV haven and lower reduction technology.

    4. Oakley Half Jacket Array: $150 These sports performance glasses are made instead of any environment. They bear down on accompanied with three interchangeable lenses so you can go beyond in any weather or light. The Half Jacket Array also includes nose pads and pedicel sleeves to resist embellish grip. These Cheap Oakleys sunglasses are an categorical must have for the sake of any outdoor sportsman.

    5. Polarized Cheap Oakley Sunglasses: $265 Don’t think I forgot about the ladies. These glasses are almost identical to the men’s Fake Oakley Sunglasses Fuente Antix, but maintain thinner stems to uncover them a more feminine feel. They also catalogue the unified lens stretching all the temperament across the glasses. You also get prominent UV bulwark as marvellously as restricted glare. The frames are made from lightweight moderate as a service to an effortless wear throughout the day.

  10. 90
    AntonioWak says:

    WILL NOT: Bitch http://www.realsmartchoice.com/ – マリークワント 長財布 about your jobRegardless with how crummy your week has got or how much people hate whatever http://www.poulsbopoa.org/ – サマンサタバサ バッグ ピンク project is shopping with an adult, your office party is not really the http://www.bagaresidency.com/ – ケイトスペード バッグ 新作 time or put to vent. Gloom is contagious, so don’t selfishly provide your colleagues down. Put on a smile and leave the work bitching for another time period. DON’T: Text http://www.jenaandaaron.com/ – アディダス オリジナルス スニーカー or talk in the president’s speechIt doesn’t matter if it is a first or 10th time you’ll hear http://www.grupoaventurapark.com/ – サマンサタバサ セール 2014 your president’s total holiday address. Be http://www.devrocks.com/ – コーチCOACH 新作 セール a good audience and give them your undivided attention. DON’T: Get blazingly http://www.hangmanclub.com/ – ゲラルディーニ バッグ ショルダー drunkThere is always someone who indulges a great deal of that the legend in their drunkenness http://www.infinite-fire.com/ – ケイトスペード バッグ 新作 follows them in to the following year. Don’t be that man or women. By all http://www.baxtersonthecrk.com/ – マークバイマークジェイコブス 時計 means, get festive over plenty of punch or eggnog, but don’t http://www.grafikdsign.com/ – グッチ 財布 アウトレット be the subject of tomorrow’s water cooler talk. Celebrate http://www.bizimstudyo.com/ – ケイトスペード 時計 moderately.

  11. 91

    Way cool! Some extremely valid points! I appreciate you penning this article and the rest
    of the site is very good.

Page 5 of 5«12345

Trackbacks

Check out what others are saying about this post...
  1. [...] in the search results.As an example of Google's fast response time, I updated my article about fixing the custom permalink bug with WP 3.1 to include a hotfix for pagination errors. Before this, there was no mention of pages or pagination [...]

  2. [...] Create a Cool 404 Page by Luke America on March 28, 2011 Leave a CommentThe recent issues with canonical redirects after upgrading to 3.1 brought my attention to the 404 Error page. Mine was rather bland and not particularly helpful. So [...]

  3. [...] full source code explanation for the prototype of this plug-in is available along with user [...]

  4. [...] note that, at this time, Tags are not functioning correctly.  This is a bug in WordPress that so far I have not been able to [...]

  5. 核桃博客 says:

    [...] 最终我选择了用下面这个文章中提到的插件来临时解决问题 http://wpcodesnippets.info/blog/how-to-fix-the-wp-3-1-custom-permalinks-bug.html [...]

  6. URL says:

    … [Trackback]

    [...] Find More Informations here: wpcodesnippets.info/?p=2189 [...]



Share Your Thoughts

(Some editor features are restricted unless you're logged in.)

(When replying to a specific comment, your browser may require Shift+Enter instead of just Enter.)


(get a gravatar)


Notify me of followup comments via e-mail. You can also subscribe without commenting.