WordPress on Routes
WordPress on Routes is a plugin for WordPress, inspired mainly by Ruby micro-frameworks. It adds ability to add custom routes to your WordPress instance. Useful for form submissions, API-like features, etc., (*1)
It's also hosted under Plugins repo: https://wordpress.org/plugins/wp-on-routes/., (*2)
Installation
Good old plugin installation applies here too - download it / clone it to plugins/
dir, activate., (*3)
No UI involved., (*4)
Basic Usage
In your functions.php:, (*5)
$routing = \WoR\Main::get_instance();
$routing->add_routes(
array(
'get' => array(
'path' => '/foo/bar',
'body' => 'Hello Buz!',
'headers' => array(
'Content-Type' => 'text/html; charset=UTF-8',
'exclude' => array(
'x-powered-by', 'x-pingback'
)
)
)
)
);
Naturally, you have to check for class existence (e.g. in lib/routes.php
file):, (*6)
if (!class_exists('\WoR\Main')) {
return;
}
And use it in functions.php
:, (*7)
require_once('lib/routes.php');
Remember, because of using namespaces your PHP installation version must be >= 5.3.0., (*8)
Extended Usage
function wor_dump() {
var_dump($_GET);
}
add_action('wor_action', 'wor_dump');
$routing = \WoR\Main::get_instance();
$routing->add_routes(
array(
'get' => array(
'path' => '/foo/*/bar/:p1?',
'action' => 'wor_action',
'agent' => '/Firefox/',
'include_template' => true
)
)
);
In example above, if you target /foo/a/b/c/bar/test
, browser will answer with HTTP status 200, with following code, with header and footer included, only in Firefox browser:, (*9)
array (size=2)
'p1' => string 'test' (length=4)
'splats' =>
array (size=1)
0 => string 'a/b/c' (length=5)
Details
At this point there are several capabilities:, (*10)
- Add custom routes to your WordPress installation
- Set method GET/POST/DELETE etc.
- Set body (as text, or template) or action (using add/do_action). If both are defined,
action
takes precedence over body
.
- Set header (e.g. 'Content-Type' => 'text/html; charset=UTF-8')
- Exclude header (e.g. 'Set-Cookie')
- Set parameters like
/my/route/:param1/:param2
or as splats /foo/*/bar
- Add agents or filter by agents, using regular expressions
- Agent filter for negative logic (e.g.
/^((?!Firefox).)*$/
, which tells "every browser except Firefox")
- Include header and footer
Options you can set:, (*11)
-
path
(string)
-
body
OR action
(string)
-
agent
(string/regex)
-
include_template
(boolean; default: false)
-
headers
(array)
Tests
Reference to tests/instructions.txt to read how to test output of your WordPress website., (*12)
I am using wp-cli to generate testing environment: https://github.com/wp-cli/wp-cli/wiki/Plugin-Unit-Tests., (*13)
So, before any testing run similar command: bash bin/install-wp-tests.sh wor_test_db root root localhost latest
., (*14)