Routing to callback functions in WordPress – 03
May 30, 2014
I've developed a working first draft of the Route
to wrap WP Router plugin functions and allow routing with as little effort as possible.
The heavy lifting is done by the plugin and mine is just an adapter class over it to use it in a way mocking what Laravel offers.
On GitHub and Packagist
The class is defined in my WordPress wrappers package; it was made to be used with Composer and it has to be required in the composer.json
file for it to be available to use
{
"require": {
"php": ">=5.3.0",
"lucatume/tdd-wrappers": "dev-master"
}
}
Downloading and inserting into custom code is a possibility though.
How much sugar?
The class allows skipping the hooking part entirely and go from code like this
// file my-routes-plugin.php
add_action('wp_router_generate_routes', 'generateMyRoutes');
function generateMyRoutes(WP_Router $router)
{
$router->add_route('wp-router-sample', array(
'path' => '^wp_router/(.*?)$',
'query_vars' => array(
'sample_argument' => 1,
),
'page_callback' => array(get_class(), 'sample_callback'),
'page_arguments' => array('sample_argument'),
'access_callback' => TRUE,
'title' => 'WP Router Sample Page',
'template' => array('sample-page.php', dirname(__FILE__).DIRECTORY_SEPARATOR.'sample-page.php')
));
}
to code like this
// file my-routes-plugin.php
use tad\wrappers\WP_Router\Route;
Route::get('wp_router/{word}', function($word){
echo "Hello $word";
})->where('word', '.*?')
->withTitle('Wp Router Sample Page')
->withTemplate(array(
'sample-page',
dirname(__FILE__).DIRECTORY_SEPARATOR.'sample-page.php'
);
If the idea is not to use any template to render the HTML code then it can get shorter but will leave all the weight of markup generation to the callback function.
Route::get('wp_router/{word}', function($word){
echo "Hello $word";
})->where('word', '.*?');
Next
In its actual implementation the class will pass all of the route arguments to the three callback functions (title_callback
, page_callback
, access_callback
) and in the same order they appear in the path; while I do not see routes with 34 arguments in my near future I can well see where the thing could become an hassle more than a real help.
Furthermore the class implements filters mocking Laravel but that's not working properly due to the arguments passing I've detailed above; I will try to get around that next.