PHPackages                             weblove/wp-router - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. weblove/wp-router

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

weblove/wp-router
=================

An ExpressJs inspired router for Wordpress

1.0.6(6y ago)85602[1 issues](https://github.com/web-love/wp-router/issues)MITPHPPHP &gt;=5.3.0

Since Apr 5Pushed 5y ago2 watchersCompare

[ Source](https://github.com/web-love/wp-router)[ Packagist](https://packagist.org/packages/weblove/wp-router)[ Docs](https://weblove.ca)[ RSS](/packages/weblove-wp-router/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (7)DependenciesVersions (8)Used By (0)

[![Wordpress router logo](https://camo.githubusercontent.com/45d201a606d40ae65e98a2dacc8b9182ffa974368971e273acb08274404f3bac/68747470733a2f2f692e6962622e636f2f6e73527a5478782f77702d726f757465722d332e706e67)](https://camo.githubusercontent.com/45d201a606d40ae65e98a2dacc8b9182ffa974368971e273acb08274404f3bac/68747470733a2f2f692e6962622e636f2f6e73527a5478782f77702d726f757465722d332e706e67)

Wordpress REST API router library
=================================

[](#wordpress-rest-api-router-library)

[![MIT license](https://camo.githubusercontent.com/63a06abfbd6e1007ebd08f4349df144974f9c9a4948be609f285be218dd89989/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7765626c6f76652f77702d726f75746572)](https://camo.githubusercontent.com/63a06abfbd6e1007ebd08f4349df144974f9c9a4948be609f285be218dd89989/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7765626c6f76652f77702d726f75746572)[![size](https://camo.githubusercontent.com/4336e12a5435529c00f5068d2f7fe9bef10ab843717b92e604742c5bac32231b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f7765622d6c6f76652f77702d726f75746572)](https://camo.githubusercontent.com/4336e12a5435529c00f5068d2f7fe9bef10ab843717b92e604742c5bac32231b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f7765622d6c6f76652f77702d726f75746572)[![version](https://camo.githubusercontent.com/e38563ecd946a23fdd721f6f923ec857cd83e644a0efd49a507937d59ed2c992/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f7765622d6c6f76652f77702d726f75746572)](https://camo.githubusercontent.com/e38563ecd946a23fdd721f6f923ec857cd83e644a0efd49a507937d59ed2c992/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f7765622d6c6f76652f77702d726f75746572)[![open issues](https://camo.githubusercontent.com/456d4661f2a70183587b172698e845512d1ab8cfc27c3870c5ce935738422a4a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f7765622d6c6f76652f77702d726f75746572)](https://camo.githubusercontent.com/456d4661f2a70183587b172698e845512d1ab8cfc27c3870c5ce935738422a4a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f7765622d6c6f76652f77702d726f75746572)

Easily write modern and reusable route middlewares for your Wordpress projects and plugins. WPRouter is inspired from the excellent [expressJs](https://expressjs.com/fr/) javascript framework. Working with Wordpress REST API will now bring you joy - instead of pain.

- Hook on already existing Wordpress REST endpoints.
- Creating your own endpoints is a breeze.
- Works with custom post types.
- Simplifies the Wordpress route regex notation for simpler `/ressource/:ressource_slug` urls.
- No dependencies, less than 400locs that simply abstract Wordpress core.

**See on:**

- [Packagist](https://packagist.org/packages/weblove/wp-router)
- [Github](https://github.com/sudomaxime/wp-router)

Getting started
---------------

[](#getting-started)

You need to have [Composer](https://getcomposer.org/) installed on your machine, [follow this link](https://getcomposer.org/doc/00-intro.md) for instructions on how to install Composer.

### Prerequisites

[](#prerequisites)

- You need to have PHP &gt;= 7.0
- Wordpress &gt;= 4.7.1

### Installing

[](#installing)

The best way to install this library is with composer:

```
$ composer require weblove/wp-router
```

### Basic example

[](#basic-example)

```
$router = new Weblove\WPRouter\Router;

$router->get("/meme/:id", function ($request, $response) {
  $params = $request->get_url_params();
  $the_meme = get_meme_by_id($params["id"]);
  $response["body"] = $the_meme;
  return $response;
});
```

The `$request` function param implements Wordpress [WP\_REST\_Request](https://developer.wordpress.org/reference/classes/wp_rest_request/) class. The `$response` param is an empty variable that can be used to pass data to the next middleware down the chain, or to send back data on your endpoint.

### Creating your first middleware

[](#creating-your-first-middleware)

Creating a middleware is a breeze. Create an anonymous function with `$request` and `$response` as parameters. A middleware custom middleware can return any type of data that is JSON serializable or an instance of [WP\_REST\_Request](https://developer.wordpress.org/reference/classes/wp_rest_request/)

```
$myCustomMiddleware = function ($req, $res) {
  $potato_id = $req->get_param("id");
  $res["potato"] = get_potato($potato_id);

  return $res;
};
```

### Returning early

[](#returning-early)

If you want to break your request early, you can return an instance of [WP\_REST\_Request](https://developer.wordpress.org/reference/classes/wp_rest_request/) as a response and the router will block executing subsequent middlewares and return that response. This can be very useful to send back errors to the API:

```
$myCustomAuthMiddleware = function ($req, $res) {
  $can_touch_this = user_can_touch_this();

  if (!$can_touch_this) {
    return new WP_REST_Response("Can't touch this", 403);
  }

  return $res;
};
```

### Chaining middlewares

[](#chaining-middlewares)

Just like expressJS, you can chain middlewares one after the other. The Router methods can take many functions as parameters. The `$response` body is simply passed to the next middleware down the chain. You can use this pattern to isolate logic in small and easy to test functions that have a single purpose:

```
$router->get("/meme/:id/category",
  function ($req, $res)
  {
    $params = $req->get_url_params();
    $the_meme = get_meme_by_id($params["id"]);
    $res["body"] = $the_meme;
    return $res;
  },
  function ($req, $res)
  {
    $meme_category_id = $res["body"]["category"]["id"];
    $meme_category_infos = get_meme_cat_infos($meme_category_id);
    $res["body"] = $meme_category_infos;
    return $res;
  }
);
```

### Hook on an existing wordpress REST endpoint

[](#hook-on-an-existing-wordpress-rest-endpoint)

You can also modify the response body of an existing wordpress endpoint with the `public hook()` method. Middlewares added to the `hook` handler will have a pre-filled `$response` parameter with the array that Wordpress would normally return to the client. You can easily modify the response before returning.

A hook request **MUST** end with a [WP\_REST\_Response](https://developer.wordpress.org/reference/classes/wp_rest_response/) class, it is possible to pass custom `$request` objects from middleware to middleware, however your last middleware (or your early breaks) must always be an instance of `WP_REST_Request`. This way you make certain that other plugins that interops with the REST API will keep working properly.

note: *You do not need to put /wp-json in your endpoint address.*

```
$router->hook('GET', '/wp/v2/posts/:id',
  $authMiddleware,
  $responseMiddleware // this function ends by returning an instance of WP_REST_Response
);
```

### Customize the default directory

[](#customize-the-default-directory)

By default your routes get added under the `/wp-json/api` directory. You can change the default behavior by providing a router parameter to the `Router` class:

```
$router = new Weblove\WPRouter\Router; // defaults to /wp-json/api
$router = new Weblove\WPRouter\Router("custom"); // now set to /wp-json/custom
```

### Public methods

[](#public-methods)

- `get(string $endpoint, middleware ...$middleware)`
- `post(string $endpoint, middleware ...$middleware)`
- `put(string $endpoint, middleware ...$middleware)`
- `delete(string $endpoint, middleware ...$middleware)`
- `patch(string $endpoint, middleware ...$middleware)`
- `hook(string $method_verb, string $endpoint, middleware ...$middleware)` - Use an already existing Wordpress endpoint.
- **In development** `use(string $endpoint, middleware ...$middleware)` - Use middlewares on all verbs of that endpoint.

### Troubleshooting and frequent errors

[](#troubleshooting-and-frequent-errors)

- My endpoint is returning an error `Uncaught Error: Call to a member function get_matched_route()` - This means you have a hook that doesn't return an instance of WP\_REST\_Response after all the middlewares have been executed. See this guide section on how to properly hook on existing wordpress endpoints.

Authors
-------

[](#authors)

- Maxime Nadeau - *initial work* - [Weblove](http://weblove.ca)

License
-------

[](#license)

This project is licensed under the MIT License - see the license.md file for details.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

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 ~4 days

Total

7

Last Release

2209d ago

### Community

Maintainers

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

---

Tags

easyexpressexpressjsmiddlewarephproutersimplewordpressmiddlewarewordpressroutereasyexpressexpressjsweblove

### Embed Badge

![Health badge](/badges/weblove-wp-router/health.svg)

```
[![Health](https://phpackages.com/badges/weblove-wp-router/health.svg)](https://phpackages.com/packages/weblove-wp-router)
```

###  Alternatives

[tgmpa/tgm-plugin-activation

TGM Plugin Activation is a PHP library that allows you to easily require or recommend plugins for your WordPress themes (and plugins).

1.8k222.5k13](/packages/tgmpa-tgm-plugin-activation)[aristath/kirki

Extending the WordPress customizer

1.3k73.0k4](/packages/aristath-kirki)[afragen/git-updater

A plugin to automatically update GitHub, Bitbucket, GitLab, or Gitea hosted plugins, themes, and language packs.

3.3k1.6k](/packages/afragen-git-updater)[hexbit/router

Wordpress Router

352.8k](/packages/hexbit-router)

PHPackages © 2026

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