Routing to callback functions in WordPress - 01
May 27, 2014
I like the way routes to endpoints can be set in Laravel: it's clear and logic and allows doing clean things like RESTful URLs in a way WordPress will sometimes not offer.
I've recently run into the need to add archive pages to the menu and got stuck with either a workaround, like adding an empty page and applying an archive template to it, or using some plugin to do so.
Can I route?
I'd like to be able to write an URL like /posts
to get the posts archive and something like /posts/some-post-title
or /posts/21
to get a specific post.
While WordPress native Rewrite API is the way to go it seems a little daunting at first and led me to more OOP approaches and solutions like WP-Router.
I can route somewhat
After installing WP-Router and setting up a plugin to use it in its main class I've hooked into the right action
class Main
{
public function __construct()
{
add_action('wp_router_generate_routes', array(
get_class() ,
'addRoutes'
));
}
to map the route to a function callback and be able to control the output with it
public static function addRoutes(\WP_Router $router)
{
$router->add_route('hello-route', array(
'path' => '^hello/(\w*?)$',
'query_vars' => array(
'name' => 1,
) ,
'page_callback' => function($name){
echo "Hello $name";
},
'page_arguments' => array(
'name'
),
'template' => false
));
}
}
the function is outputting to the page and using that route parameter to show an output, once the plugin is activated and I enter the /hello/world
URL the message, and that alone, is shown on the page [caption id="attachment_1030" align="aligncenter" width="1024"][](http://theaveragedev.local/wordpress/wp-content/uploads/2014/05/2014-05-27-at-18.28.png) Hello world output[/caption] please note that any theme layout and template is ignored and not shown on the page; the only output is the one that the callback function, a closure here, is producing.
In a Laravel-like fashion it allows using functions to show content on the page. The interface the plugin offers, though, is not that easy to grasp.
Next
I like WP-Router so far and would like to create an adapter/wrapper class around it to model its interface on the one used by Laravel like
Route::get('/landing', function(){
echo 'Hello world';
});
That's possible using a function like
$router->add_route('root-route', array(
'path' => 'landing',
'page_callback' => function(){
echo "Hello world";
},
'template' => false
));
but that sure is more code than Laravel's solution.