Permalinks

WordPress comes with a nifty feature called Permalinks, whereby you can have links to your articles by name, rather than by the icky ID number.

I’ve never done that, because the rewrite rules necessary to make it happen are deeply inscrutable.

Well, since I’m monkeying with mod_rewrite stuff anyway, I thought that making a permalink thingy that I can actually understand would be a good example of a RewriteMap rule. So, here it is.

This is a first draft, and may have some problems. I already know one problem, and that is that RewriteMap can’t be used in .htaccess files. That’s not a problem for me, but it is a problem for a significant number of folks that use WordPress. The only way around that is to get your server admin to add a RewriteMap line to the main server config file, pointing at your map program. That problem may be insurmountable for some folks.

Anyways, in your config file, you put:

RewriteMap wp_permalinks prg:/somewhere/bin/wp_rewrite_map.pl
RewriteRule ^/perm/(.*) ${wp_permalinks:$1} [PT]

The file /somewhere/bin/wp_rewrite_map.pl looks like this:

#!/usr/bin/perl
use DBI;
$|=1;
my $dbh = DBI->connect(“DBI:mysql:wordpress:dbserver”, ‘username’, ‘password’);
my $sth = $dbh->prepare(“SELECT ID FROM wp_posts
WHERE post_name = ?”);
my $ID;

# Rewrite “permalink” style links to article IDs

while (my $post_name = <STDIN>) {
chomp $post_name;
$sth->execute($post_name);
$sth->bind_columns($ID);
$sth->fetch;

print “/wordpress/index.php?p=$IDn”;
}

This article, for example, has the URL of https://drbacchus.com/perm/permalinks