[00] Subset Redirects, For developers
Developer reference
Subset Redirects' actions and filters, CSV format, WP-CLI commands and REST API, plus what Pro adds.
This page lists everything you can use to work with Subset Redirects from code: hooks, the CSV format, WP-CLI commands and the REST API. Every hook name starts with subset_redirect_.
The redirect array
Hooks that pass a redirect pass an array with these keys:
| Key | Type | Notes |
|---|---|---|
id | int | |
source | string | The normalized URL to redirect from. |
target | string | A path relative to the home URL, or a full URL. '' for a 410. |
status_code | int | 301, 302 or 410. |
query_mode | string | ignore, exact or pass-through. |
match_type | string | exact. Pro adds wildcard and regex. |
enabled, external | bool | |
group_name, notes | string | |
origin | string | manual, slug-change, import, migration or suggestion. |
hits | int | |
last_hit_at, created_at, updated_at | string|null | MySQL datetimes in UTC. |
How matching works
Every redirect source, incoming request and 404 log entry is normalized the same way, and two URLs match when they normalize to the same string. A normalized URL is a path relative to the home URL, plus a query string if there is one:
| You enter | Stored as |
|---|---|
/About/Team/ | /about/team |
https://example.com/about/ (this site) | /about |
/café | /caf%C3%A9 |
/search/?q=red+shoes&page=2#results | /search?page=2&q=red%20shoes |
When more than one enabled redirect matches, a source with the exact query string wins, then a path match, then the oldest redirect. Redirects only apply to front-end requests: never to wp-admin, admin-ajax.php, wp-cron.php, wp-login.php, xmlrpc.php, WP-CLI or the REST API.
Actions and filters
Redirecting
These run, in this order, on a front-end request that matches an enabled redirect.
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_before_redirect | filter | bool $apply, array $redirect, string $request | Return false to let the request continue as if the redirect didn’t exist. |
subset_redirect_count_hit | filter | bool $count, array $redirect | Return false to skip counting this hit. Each counted hit is one UPDATE. |
subset_redirect_hit_counted | action | array $redirect, string $request | Fires after a hit is counted. Anything slow here slows every redirect. |
subset_redirect_redirect_target | filter | string $target, array $redirect, string $request | Change the absolute URL a 301 or 302 sends the visitor to. |
subset_redirect_did_redirect | action | array $redirect, string $target, string $request | Fires before the response is sent. $target is '' for a 410. |
Let logged-in editors see the old page:
add_filter( 'subset_redirect_before_redirect', function ( $apply ) {
return $apply && ! current_user_can( 'edit_posts' );
} );
Tag visitors who arrive from retired campaign URLs:
add_filter( 'subset_redirect_redirect_target', function ( $target, $redirect ) {
return 'campaigns' === $redirect['group_name'] ? add_query_arg( 'from', 'old-campaign', $target ) : $target;
}, 10, 2 );
Matching
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_normalize_url | filter | string $normalized, string $original | Change how URLs are normalized. It applies to sources, requests and 404s alike. |
subset_redirect_match_types | filter | array $types | Labels by match type, like [ 'exact' => 'Exact URL' ]. exact is always kept. |
subset_redirect_prepare_source | filter | string|WP_Error|null $source, string $raw_source, string $match_type, string $query_mode | Store the source for a custom match type, or return a WP_Error to refuse it. |
subset_redirect_find | filter | array|null $redirect, string $normalized, int $exclude_id | Return a redirect of your own match type when no exact redirect matches. Runs on every unmatched request. |
subset_redirect_resolve_target | filter | string $target, array $redirect, string $normalized | Fill in a custom match type’s target, before it’s made absolute. |
Ignore utm_* tracking parameters everywhere:
add_filter( 'subset_redirect_normalize_url', function ( $url ) {
$parts = explode( '?', $url, 2 );
if ( ! isset( $parts[1] ) ) {
return $url;
}
$query = implode( '&', array_filter( explode( '&', $parts[1] ), function ( $pair ) {
return 0 !== strpos( $pair, 'utm_' );
} ) );
return '' === $query ? $parts[0] : "{$parts[0]}?{$query}";
} );
Changing normalization doesn’t update redirects you’ve already saved. Save them again, or export and re-import them.
Saving redirects
These fire for changes from the admin screen, imports, WP-CLI, REST and automatic redirects.
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_redirect_saved | action | array $redirect, array|null $old | Fires after a redirect is created or changed. $old is null for a new one. |
subset_redirect_redirect_deleted | action | array $redirect | Fires after a redirect is deleted. |
Automatic redirects
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_auto_redirect_post_types | filter | string[] $types | Post types whose URL changes are redirected. Defaults to the settings, or every public type except attachments. |
subset_redirect_auto_redirect_taxonomies | filter | string[] $taxonomies | Taxonomies whose term URL changes are redirected. Defaults to the settings, or every public taxonomy except post formats. |
404 log
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_ignore_404 | filter | bool $ignore, string $url, string $user_agent | Return true to leave a 404 out of the log. |
subset_redirect_404_columns | filter | array $columns | Add columns to the 404 Log table. |
subset_redirect_404_column | action | string $column_name, array $item | Print a cell for a column you added. Escape your output. |
subset_redirect_404_table_items | action | array $items | Fires once per page of the table, so a column can load its data in one query. |
subset_redirect_404_row_actions | filter | array $actions, array $item | Change a row’s action links. |
subset_redirect_404_bulk_actions | filter | array $actions | Add bulk actions. The built-in ones can’t be removed. |
subset_redirect_404_bulk_action | action | string $action, array $ids | Handle a bulk action you added. The nonce and capability are already checked. |
subset_redirect_404_tools | action | array $filters | Print your own tool after Ignore a pattern and Clear the log. |
Don’t log missing images:
add_filter( 'subset_redirect_ignore_404', function ( $ignore, $url ) {
return $ignore || preg_match( '/\.(jpe?g|png|gif|webp)$/', $url );
}, 10, 2 );
Page caches
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_purge_urls | filter | string[] $urls, array $redirect | The absolute URLs purged when a redirect is saved or deleted. |
subset_redirect_purge_url | action | string $url | Fires for each purged URL. Use it to purge a host cache or CDN. |
subset_redirect_page_caches | filter | string[] $caches | The active page caches Site Health reports. |
Purge a CDN when a redirect changes:
add_action( 'subset_redirect_purge_url', function ( $url ) {
wp_remote_post( 'https://cdn.example/purge', [ 'body' => [ 'url' => $url ], 'blocking' => false ] );
} );
Settings and admin
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_settings | filter | array $settings | Pin a setting in code, whatever is saved. See SubsetRedirect\Settings::defaults() for the keys. |
subset_redirect_capability | filter | string $capability | The capability needed to manage redirects, in the admin and over REST. Default manage_options. |
subset_redirect_admin_tabs | filter | array $tabs | Add a tab to Subset → Redirects. Each tab has a label, a load callback and a render callback. |
subset_redirect_redirect_form_rows | action | array $values | Print extra rows at the end of the add/edit redirect form. |
subset_redirect_list_filters | filter | array $filters | Read and sanitize a custom filter for the redirects list. |
subset_redirect_list_filter_controls | action | array $filters | Print a custom filter’s control. |
subset_redirect_list_query_args | filter | string[] $keys | Query arguments kept on links that show the same filtered list. |
subset_redirect_search_clauses | filter | array $clauses, array $args | Add SQL conditions to Redirects::search(), which the list, CSV export, REST and WP-CLI all use. |
subset_redirect_docs_url | filter | string $url | The documentation link Site Health shows. |
Turn off the 404 log in code:
add_filter( 'subset_redirect_settings', function ( $settings ) {
$settings['log_mode'] = 'off';
return $settings;
} );
Let editors manage redirects:
add_filter( 'subset_redirect_capability', function () {
return 'edit_others_posts';
} );
Install and uninstall
| Hook | Type | Arguments | What it does |
|---|---|---|---|
subset_redirect_upgrade | action | string|false $installed, string $version | Fires the first time a site runs a new version, including a fresh install. Make handlers safe to run twice. |
subset_redirect_activate | action | none | Fires on activation for each site set up. |
subset_redirect_deactivate | action | none | Fires on deactivation for each site. |
subset_redirect_delete_data_on_uninstall | filter | bool $delete | Whether deleting the plugin deletes this site’s data. Add it from a must-use plugin. |
You can also define SUBSET_REDIRECT_DELETE_DATA_ON_UNINSTALL in wp-config.php to decide for a whole network.
Import sources
subset_redirect_import_sources filters the plugins you can import from. Add an instance of a class that extends SubsetRedirect\Import\Source and implements key(), name(), available() and rows(). rows() returns rows in the CSV format, numbered from 1:
class My_Old_Plugin_Source extends \SubsetRedirect\Import\Source {
public function key() { return 'my-old-plugin'; }
public function name() { return 'My Old Plugin'; }
public function available() { return (bool) get_option( 'my_old_redirects' ); }
public function rows() {
$rows = [];
foreach ( (array) get_option( 'my_old_redirects' ) as $from => $to ) {
$rows[ count( $rows ) + 1 ] = self::row( $from, $to, 301 );
}
return $rows;
}
}
add_filter( 'subset_redirect_import_sources', function ( $sources ) {
$sources[] = new My_Old_Plugin_Source();
return $sources;
} );
CSV format
Import and export use the same format. The first row names the columns, and only source is required:
| Column | Values |
|---|---|
source | The URL to redirect from. |
target | Where to send visitors. Empty for a 410. |
status_code | 301 (default), 302 or 410. |
query_mode | ignore (default), exact or pass-through. |
enabled | 1/0, yes/no or true/false. Defaults to enabled. |
group | Group name. |
notes | Notes. |
external | Whether the target may be on another site. Same values as enabled. |
match_type | exact (default). With Pro, also wildcard or regex. |
source,target,status_code,query_mode,enabled,group,notes,external,match_type
/old-page,/new-page,301,ignore,1,,,0,exact
/discontinued-widget,,410,ignore,1,,No replacement,0,exact
A row whose source matches an existing redirect updates it, and an identical row is skipped. Invalid rows are reported with their line number. Files can be up to 2 MB and 10,000 rows.
WP-CLI
Every command lives under wp subset redirector and uses the same validation as the admin screen. WP-CLI commands lists each one with its options, defaults and examples, free and Pro.
REST API
The namespace is subset-redirect/v1. Every route needs a user with the plugin’s capability (manage_options by default). Authenticate with a cookie and an X-WP-Nonce header, or with an application password. Invalid input returns a 400 with the same message the admin screen shows.
| Route | Methods | What it does |
|---|---|---|
/redirects | GET, POST | List or create redirects. |
/redirects/<id> | GET, POST/PUT/PATCH, DELETE | Read, change or delete a redirect. |
/redirects/test | POST | What a visit to url does. The same check as Test a URL. |
/404s | GET | List logged 404s. |
/404s/<id> | GET, POST/PUT/PATCH, DELETE | Read an entry, set its status to open, ignored or resolved, or delete it. |
Redirect objects use the same fields as the redirect array above, except the group is group rather than group_name. List routes take page and per_page (up to 1000) and return X-WP-Total and X-WP-TotalPages headers.
curl -u admin:APP_PASSWORD -X POST https://example.com/wp-json/subset-redirect/v1/redirects \
-H 'Content-Type: application/json' \
-d '{"source": "/old-page", "target": "/new-page"}'
A redirect that would create a loop is refused with the code subset_redirect_loop.
Pro
Pro adds these for developers:
| Name | Type | What it does |
|---|---|---|
wildcard, regex | match types | Use them as match_type in the CSV, REST API and --match-type. $1 in the target is the first capture. |
wp subset redirector server-rules apache|nginx | command | Print your redirects as Apache or nginx rules. Nothing is written to your server. |
subset_redirect_pro_loaded | action | Fires once Pro has confirmed the free plugin is active. |
subset_redirect_pro_batch_hits | filter | Return true to batch hit statistics in a persistent object cache. |
subset_redirect_pro_hit_days | filter | How many days of daily hit statistics to keep. Default 400. |
A wildcard source like /old/* matches any text, slashes included. A regex source runs against the whole normalized URL, so /old matches only /old. Pattern redirects only get a turn when no exact redirect matches, and Pro refuses a regex that backtracks badly when you save it.
Testing redirects
Check the status code as well as the destination. A redirect that turned into a 302 by mistake still passes a test that only checks where the request ended up:
curl -sS -o /dev/null -w '%{http_code} %{redirect_url}\n' https://example.com/old-page
Expect 301 https://example.com/new-page. Leave out -L, because following redirects would hide a chain.