My blog archive URLs were like:
http://example.com/2014/03
I changed my site’s permalink from /%postname%/
to /%postid%/%postname%/
, and using Redirection plugin, I set a redirection like:
and it’s working. But the problem occurs in the archive URLs. The new archive URL generated with a /date/ basename before the dates, like:
http://example.com/date/2014/03
I’m trying to use the same Redirection plugin to redirect the URL, but failed:
I then tried writing .htaccess
on my own (with no .htaccess
writing experience) with:
Redirect permanent http://example.com/([0-9]+)/([0-9]+) http://example.com/date/([0-9]+)/([0-9]+)
with the help of htaccess editor and this blog. But failed too.
How can I let my blog not to get 404 on such archive URL? I’m afraid, I’m dumb with rewrite rule till now. 🙁
I’m working on a plugin that handle things like that. While it’s in development I want to share some code derived form my plugin that can help you, I hope.
If you look at your sources urls, they are easily to be recognize: you have 2 cases in which you need to redirect:
Looking at pieces count is very easy, is a matter of a
count()
and aexplode()
, looking at valid post slug needs to be queried in database.Workflow
/%year%/%monthnum%
and if so redirectThe number #3 can be improved in performance using transient-based cache.
1. Get the url
Let’s write a function that get the url pieces. It must strips the
home_url()
part from urls.2. Explode the url pieces and count them: if count isn’t 1 or 2 do nothing
This part of workflow should be run as easy as possible,
'after_setup_theme'
is a good place, because is available for both plugins and url and is pretty early.3. Checking url pieces and apply redirect if needed
First function for 2 pieces urls
Second function for 1 pieces urls
Implementing cache