PHPackages                             ssnepenthe/simple-wp-routing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. ssnepenthe/simple-wp-routing

ActiveLibrary

ssnepenthe/simple-wp-routing
============================

Syntactic sugar over the WP\_Rewrite API so we can pretend that WordPress has a modern router.

0.1.1(2y ago)03871MITPHPPHP ^7.4 || ^8.0

Since Aug 24Pushed 2y ago2 watchersCompare

[ Source](https://github.com/ssnepenthe/simple-wp-routing)[ Packagist](https://packagist.org/packages/ssnepenthe/simple-wp-routing)[ RSS](/packages/ssnepenthe-simple-wp-routing/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (14)Versions (8)Used By (0)

simple-wp-routing
=================

[](#simple-wp-routing)

Syntactic sugar over the `WP_Rewrite` API so we can pretend that WordPress has a modern router.

Warning
-------

[](#warning)

This package is currently in development and is subject to breaking changes without notice until v1.0 has been tagged.

It is one in a series of [WordPress toys](https://github.com/ssnepenthe?tab=repositories&q=topic%3Atoy+topic%3Awordpress&type=&language=&sort=) I have been working on with the intention of exploring ways to modernize the feel of working with WordPress.

As the label suggests, it should be treated as a toy.

Installation
------------

[](#installation)

```
composer require ssnepenthe/simple-wp-routing
```

Basic Usage
-----------

[](#basic-usage)

Intended usage is via the Router class.

### Overview

[](#overview)

```
use SimpleWpRouting\Exception\NotFoundHttpException;
use SimpleWpRouting\Responder\JsonResponder;
use SimpleWpRouting\Router;

// Create a router instance.
$router = new Router();

// Optional - configure your router via various available setters.
// At a minimum it is recommended to set a route prefix in order to avoid conflicts with core and other plugins.
$router->setPrefix('pfx_');

// Wire your router up with WordPress.
$router->initialize(

  // The initialize method accepts a callback which is where you should add all of your routes.
  function (Router $router) {

    // Routes are registered via HTTP method shortcuts on the router instance.
    $route = $router->get(

      // Route syntax comes from FastRoute.
      'api/users/{user}',

      // Route handlers are automatically invoked for their corresponding route/HTTP method pair.
      function (array $vars) {

        // Handlers receive an array of matched route variables by default.
        $user = getUserDataById((int) $vars['user']);

        // HTTP exceptions are automatically converted to error responses.
        if (null === $user) {
          throw new NotFoundHttpException();
        }

        // Handlers can optionally return a responder instance.
        return new JsonResponder($user);
      }
    );

    // Routes can optionally be configured with an active callback.
    $route->setIsActiveCallback(function () {

      // Return true to enable this route, false to disable it.
      return isApiUserEndpointEnabled();
    });
  }
);
```

### Route Syntax

[](#route-syntax)

The default route syntax comes from FastRoute.

Route variables are wrapped in curly brackets and match the regex pattern `[^/]+` by default (e.g. `users/{user}`). Custom regex patterns can be provided using a `name:pattern` syntax (e.g. `users/{user:\d+}`). Capture groups are not allowed in custom patterns.

Optional route segments are defined using square brackets (e.g. `users/{user}[/favorites]`). Nested optional segments are also supported (e.g. `users[/{user}[/favorites]]`). Optional segments are only supported at the end of route strings.

If you have a route syntax that you prefer over FastRoute, you can provide a custom route parser. Your parser must implement `\SimpleWpRouting\Parser\RouteParserInterface`. Refer to the included `tests/Unit/Parser/FastRouteRouteParserTest.php` file to understand route parser requirements.

### Route Handlers

[](#route-handlers)

Route handlers are automatically called within the `'parse_request'` hook when their corresponding route/method pair matches the current request.

Allowed types for handlers are defined by the callable resolver. With the default config, handlers must be a PHP callable. If using the PSR container callable resolver, handlers may also be a string identifier that resolves a callable from your container or a callable shaped array where index 0 is a string identifier that resolves an object from your container and index 1 is a callable method on that object.

The function signature is defined by the configured invoker. The default invoker provides an array containing all matched route variables keyed by variable name. The PHP-DI invoker provides matched route variables directly by name.

HTTP exceptions can be used as a convenient escape hatch from handlers.

#### NotFoundHttpException

[](#notfoundhttpexception)

This is currently the only non-internal HTTP exception and can be used to show a 404 page.

```
use SimpleWpRouting\NotFoundHttpException;

$router->get('books/{book}', function (array $vars) {
  if (! $book = getBookById($vars['book'])) {
    throw new NotFoundHttpException();
  }

  // ...
});
```

Route handlers can optionally return an instance of `SimpleWpRouting\Responder\ResponderInterface`. The `respond` method on the returned responder will automatically be invoked on the WordPress `parse_request` action.

This allows common behavior to easily be wrapped up for reuse.

The following basic responder implementations are included:

#### JsonResponder

[](#jsonresponder)

```
use SimpleWpRouting\Responder\JsonResponder;

$router->get('api/products', function () {
  return new JsonResponder(['products' => getAllProducts()]);
});
```

Responses are sent using `wp_send_json_success` or `wp_send_json_error` depending on the status code, so data will be available at `response.data`.

#### QueryResponder

[](#queryresponder)

```
use SimpleWpRouting\Responder\QueryResponder;

$router->get('products/random[/{count}]', function (array $vars) {
  $count = (int) ($vars['count'] ?? 5);

  return new QueryResponder([
    'post_type' => 'pfx_product',
    'orderby' => 'rand',
    'posts_per_page' => clamp($count, 1, 10),
  ]);
});
```

Query variables are applied on the `parse_request` hook, before the main query is run.

#### RedirectResponder

[](#redirectresponder)

```
use SimpleWpRouting\Responder\RedirectResponder;

$router->get('r/{redirect}', function (array $vars) {
  $location = getRedirectLocationById($vars['redirect']);

  return new RedirectResponder($location);
});
```

Redirects are sent using `wp_safe_redirect` by default. You can pass `false` as the 4th constructor argument to use `wp_redirect` instead:

```
return new RedirectResponder($location, 302, 'WordPress', false);
```

#### TemplateResponder

[](#templateresponder)

```
use SimpleWpRouting\Responder\TemplateResponder;

$router->get('thank-you', function () {
  return new TemplateResponder(__DIR__ . '/templates/thank-you.php');
});
```

Templates are loaded via the `template_include` filter.

### Active Callbacks

[](#active-callbacks)

Allowed types for active callbacks are also defined by the configured callable resolver.

Active callbacks should return a boolean value - when true the route will be considered active, when false the route will be considered inactive.

Rewrite rules and query variables for inactive routes are still registered with WordPress, but visiting the route will result in a 404 response.

### Error Templates

[](#error-templates)

Basic 400 and 405 error templates are included with styling loosely modeled after the twentytwentytwo 404 template.

These can be overridden in themes by creating `400.php` and `405.php` templates or `400.html` and `405.html` block templates.

### Likely Changes

[](#likely-changes)

Types of various SPL exceptions used throughout the package as well as revisiting the general hierarchy of package exceptions.

Responder internals - partials concept is a bit convoluted/over-engineered. Any changes shouldn't affect the top-level responders meant for use by end-users.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~44 days

Total

2

Last Release

856d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/acf42baca29dd8d1ffaf61009a3000068423a84db153c5cb864ef6fde64a1b87?d=identicon)[ssnepenthe](/maintainers/ssnepenthe)

---

Top Contributors

[![ssnepenthe](https://avatars.githubusercontent.com/u/10903810?v=4)](https://github.com/ssnepenthe "ssnepenthe (97 commits)")

---

Tags

toywordpress

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ssnepenthe-simple-wp-routing/health.svg)

```
[![Health](https://phpackages.com/badges/ssnepenthe-simple-wp-routing/health.svg)](https://phpackages.com/packages/ssnepenthe-simple-wp-routing)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
