September 29, 2023

Creating Custom Route URLs in WordPress Using WordPress Dispatcher

When developing WordPress themes or plugins, we often need to create custom pages or implement Ajax functionality. Traditionally, this is done using the admin-ajax.php endpoint for Ajax, and by manually creating pages via the WordPress admin panel. But is there a cleaner, more code-centric way to do this—without creating backend pages or relying on admin-ajax.php?

The answer is yes. With the help of the WordPress Dispatcher PHP library, you can set up clean and intuitive custom routes, bypassing WordPress’s default approach.


Why Use WordPress Dispatcher?

WordPress Dispatcher allows developers to define route-based URLs that map directly to functions or controllers, enabling:

  • Lightweight routing for Ajax or custom page responses
  • Clean URLs like /online_charge/ or /orders/status/
  • Separation of logic and presentation using templates
  • A more maintainable and MVC-style architecture for WordPress development

Installing WordPress Dispatcher via Composer

The easiest way to integrate WordPress Dispatcher into your project is using Composer. Run the following command in your project root:

composer require thefold/wordpress-dispatcher

Once installed, include Composer’s autoloader in your plugin or theme:

require_once( dirname( __FILE__ ) . '/../vendor/autoload.php' );

use TheFold\WordPress\Dispatch;

Example 1: Creating a Custom Ajax Endpoint – Online Recharge

Here’s an example from a recent project where I needed to create an online recharge endpoint. Instead of routing through admin-ajax.php, we define a clean URL /online_charge/ that triggers a function directly:

new Dispatch([
    'online_charge' => function($request) {
        $mount = trim($_POST['mount']);
        $tn = "p4" . order_no(); // Generate unique order number

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

        $options = [
            'out_trade_no' => $tn,
            'subject' => 'Online Recharge',
            'total_fee' => $total_fee,
        ];

        $gateway = get_gate_way(); // Your payment gateway logic
        $response = $gateway->purchase($options)->send();

        $response->redirect(); // Redirect to payment page (e.g., Alipay)
    },
]);

Now when an Ajax request is sent to /online_charge/, this function gets executed automatically.


Example 2: Using a Custom Template Instead of a Callback

If you prefer to display a full custom page (without creating one in the WP admin), you can load a PHP template file directly in your route:

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

In this setup, URLs like /orders/pending/ or /orders/completed/ will load your page-orders.php template, where $status can be used dynamically.


Example 3: Organizing Routes with Controllers

For larger applications, organizing your routes using controller classes improves maintainability:

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

This approach gives your application a cleaner structure, similar to modern MVC frameworks like Laravel or Symfony.


Conclusion

WordPress Dispatcher is a powerful tool for developers who want to break away from WordPress’s built-in limitations around routing and Ajax. By using it, you:

  • Avoid cluttering your backend with unnecessary pages
  • Eliminate admin-ajax.php for custom Ajax endpoints
  • Maintain cleaner and more scalable code

Whether you’re building a plugin, theme, or full-featured application on WordPress, Dispatcher can be a game-changer.