Use WordPress Dispatcher to Create Custom Routes and URLs in WordPress

In standard WordPress development, Ajax handlers are usually registered on admin-ajax.php, and if we need a new front-end page we often create it from the dashboard. But there are times when we want a cleaner custom URL without creating a physical page in the back end, and without routing everything through admin-ajax.

That is where the WordPress Dispatcher library becomes useful. It can be bundled directly into a theme or plugin, but the easiest option is to install it through Composer.

Install WordPress Dispatcher with Composer

WordPress Dispatcher is available through Composer, so installation is simple:

composer require thefold/wordpress-dispatcher

Load the library through Composer’s autoload file

After Composer finishes installation, it generates an autoload file for all installed packages. Including that file gives the theme or plugin access to the WordPress Dispatcher classes automatically.

// Load Composer-installed libraries
require_once( dirname( __FILE__ ) . '/../vendor/autoload.php' );

use TheFoldWordPressDispatch;

Create custom WordPress URLs with WordPress Dispatcher

As an example, imagine an online recharge feature. In the code below, online_charge is the custom URL route. Ajax submits data to /online_charge/, the matching callback runs automatically, an order is created, and the user is redirected to Alipay.

// Online recharge
new Dispatch( [

 'online_charge' => function ( $request ) {

   $mount = trim( $_POST['mount'] );
   $tn = "p4" . order_no();

   // Calculate the total amount
   $total_fee = array_sum( $mount );

   // Create the order data
   $options = [
     'out_trade_no' => $tn,
     'subject' => '在线充值',
     'total_fee' => $total_fee,
   ];

   // Get the payment gateway
   $gateway = get_gate_way();

   $response = $gateway->purchase( $options )->send();

   // Redirect directly to Alipay
   $response->redirect();
 },

] );

Use a custom template instead of putting everything in the callback

Sometimes the callback should not generate the output itself. In that case, it can simply include a custom template file, and variables from the URL can still be used in that template.

new Dispatch( [

	'orders/([a-z]*)' => function ( $request, $status="all" ) {
		include( get_template_directory() . '/page-orders.php' );
	},

] );

You can also route directly to methods on a controller-style class, which is often a cleaner way to organize larger applications:

new Dispatch([
    'checkout/'         => [new CheckoutController, 'index'],
    'checkout/([a-z]+)' => [new CheckoutController, 'show', [$request, $id]],
    // In the parameters above, $request = checkout/([a-z]+); $id = ([a-z]+);
]);

With WordPress Dispatcher, we can bypass the usual admin-ajax registration pattern for many custom workflows. In themes or plugins that need a lot of Ajax-like interactions, this can save a considerable amount of code and make the routing logic much clearer.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *