Custom routing for the adventurous
Every time I read a post from Carl Alexander, I think, “Neat, now show me more examples of this in action!” This one is no different, where he describes how to build a custom routing system for WordPress.
If you’re like me, and wonder why the heck you’d do that, because you have the rewrite API of WordPress itself, well, he’s accounted for us:
But isn’t this the job of the rewrite API?
Not quite. (But excellent question!) The rewrite API allows WordPress to understand human-readable URLs. There’s no question that it’s an important task.
That said, a routing system is a large enough problem that it’s made up of smaller sub-problems. Solving these sub-problems is necessary for the routing system to do its job. And, as you’ll see next, the rewrite API itself only takes care of one of these sub-problems.
And then he goes on to explain in detail (which will be nice for those of you that ever actually tackle this) how to build a custom routing system.
So now the question still remains: Where are the examples? I know there are good use cases for custom routing, but an expansive system like he’s written still seems a bit overkill when most of us might accomplish what we want with one or two extra rewrite rules.
So I went to #heavydev in Slack and Remkus came to my rescue. They build a heavy duty routing system for a client that has combined taxonomies and custom post types, all with pretty permalinks. So the URL might look like this:
And so on. It can certainly get wild, especially if you have highly structured content. You can even do it where there’s a range of acceptable data, like this live URL Remkus sent me (non-English language alert!).
So anyway, Carl’s post is neat. But if he were reading this, I’d ask for more examples. Thanks Remkus for the URLs and Daan for the code 😉
Now, most of you don’t need this. But all of you need to know how WordPress URLs end up sending a query to the database. Erick Hitter has you covered, in this talk that was one of the more informative I’ve ever seen.