Better Permalinks to Pages

Tuesday, November 1st, 2005 - Español English

For some obscure reason, using WordPress Pages together with permalinks did not work for me with latest WP installed (1.5.2). Here is my solution together with the modifications to the code.

Looking at the apache mod_rewrite rules automatically built by WP in the control panel, I saw that the name of each Page is harcoded into the 5 rules:


RewriteRule ^(yawl)/trackback/?$ /index.php?pagename=$1&tb=1 [QSA,L]
RewriteRule ^(yawl)/feed/(feed|rdf|rss|rss2|atom)/?$ /index.php?pagename=$1&feed=$2 [QSA,L]
RewriteRule ^(yawl)/(feed|rdf|rss|rss2|atom)/?$ /index.php?pagename=$1&feed=$2 [QSA,L]
RewriteRule ^(yawl)/page/?([0-9]{1,})/?$ /index.php?pagename=$1&paged=$2 [QSA,L]
RewriteRule ^(yawl)(/[0-9]+)?/?$ /index.php?pagename=$1&page=$2 [QSA,L]

This is obviusly quite ugly if it means that I have to modify the rules each time I add a new Page (I guess that adding alternatives to the first capture pattern in the regular expression of each rule), so I’ve hacked a couple of modifications:

The code

Somewhere around line 1002 of file wp-includes/classes.php, inside function WP_Rewrite::get_page_permastruct(), I changed:

$this->page_structure = $this->root . '%pagename%';

to:

$this->page_structure = $this->root . $this->page_base . '/%pagename%';

But first we have to add the variable page_base to class WP_Rewrite, so as to use the same principle as with posts, searchs, etc. At the beginning of the class (around line 750) we write:

var $page_base = 'pages';

This should be enough to have get_page_link(), of wp-includes/template-functions-links.php build the links to the pages using /pages/%pagename/ if permalinks are on.

Apache rules

Based upon the WP generated rules, I’ve built the following ones:


RewriteRule ^pages/([^/]+)/trackback/?$ /index.php?pagename=$1&tb=1 [QSA,L]
RewriteRule ^pages/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ /index.php?pagename=$1&feed=$2 [QSA,L]
RewriteRule ^pages/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ /index.php?pagename=$1&feed=$2 [QSA,L]
RewriteRule ^pages/([^/]+)/page/?([0-9]{1,})/?$ /index.php?pagename=$1&paged=$2 [QSA,L]
RewriteRule ^pages/([^/]+)(/[0-9]+)?/?$ /index.php?pagename=$1&page=$2 [QSA,L]

That’s all. I guess that for the sake of consistency in the code, one should at least modify
WP_Rewrite::generate_rewrite_rules() and WP_Rewrite::page_rewrite_rules() as well to enable the user to generate this rules automatically, but I’m too lazy now…

The result

It works: Yawl.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>