Skip to content

[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:

KeyTypeNotes
idint
sourcestringThe normalized URL to redirect from.
targetstringA path relative to the home URL, or a full URL. '' for a 410.
status_codeint301, 302 or 410.
query_modestringignore, exact or pass-through.
match_typestringexact. Pro adds wildcard and regex.
enabled, externalbool
group_name, notesstring
originstringmanual, slug-change, import, migration or suggestion.
hitsint
last_hit_at, created_at, updated_atstring|nullMySQL 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 enterStored 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.

HookTypeArgumentsWhat it does
subset_redirect_before_redirectfilterbool $apply, array $redirect, string $requestReturn false to let the request continue as if the redirect didn’t exist.
subset_redirect_count_hitfilterbool $count, array $redirectReturn false to skip counting this hit. Each counted hit is one UPDATE.
subset_redirect_hit_countedactionarray $redirect, string $requestFires after a hit is counted. Anything slow here slows every redirect.
subset_redirect_redirect_targetfilterstring $target, array $redirect, string $requestChange the absolute URL a 301 or 302 sends the visitor to.
subset_redirect_did_redirectactionarray $redirect, string $target, string $requestFires 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

HookTypeArgumentsWhat it does
subset_redirect_normalize_urlfilterstring $normalized, string $originalChange how URLs are normalized. It applies to sources, requests and 404s alike.
subset_redirect_match_typesfilterarray $typesLabels by match type, like [ 'exact' => 'Exact URL' ]. exact is always kept.
subset_redirect_prepare_sourcefilterstring|WP_Error|null $source, string $raw_source, string $match_type, string $query_modeStore the source for a custom match type, or return a WP_Error to refuse it.
subset_redirect_findfilterarray|null $redirect, string $normalized, int $exclude_idReturn a redirect of your own match type when no exact redirect matches. Runs on every unmatched request.
subset_redirect_resolve_targetfilterstring $target, array $redirect, string $normalizedFill 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.

HookTypeArgumentsWhat it does
subset_redirect_redirect_savedactionarray $redirect, array|null $oldFires after a redirect is created or changed. $old is null for a new one.
subset_redirect_redirect_deletedactionarray $redirectFires after a redirect is deleted.

Automatic redirects

HookTypeArgumentsWhat it does
subset_redirect_auto_redirect_post_typesfilterstring[] $typesPost types whose URL changes are redirected. Defaults to the settings, or every public type except attachments.
subset_redirect_auto_redirect_taxonomiesfilterstring[] $taxonomiesTaxonomies whose term URL changes are redirected. Defaults to the settings, or every public taxonomy except post formats.

404 log

HookTypeArgumentsWhat it does
subset_redirect_ignore_404filterbool $ignore, string $url, string $user_agentReturn true to leave a 404 out of the log.
subset_redirect_404_columnsfilterarray $columnsAdd columns to the 404 Log table.
subset_redirect_404_columnactionstring $column_name, array $itemPrint a cell for a column you added. Escape your output.
subset_redirect_404_table_itemsactionarray $itemsFires once per page of the table, so a column can load its data in one query.
subset_redirect_404_row_actionsfilterarray $actions, array $itemChange a row’s action links.
subset_redirect_404_bulk_actionsfilterarray $actionsAdd bulk actions. The built-in ones can’t be removed.
subset_redirect_404_bulk_actionactionstring $action, array $idsHandle a bulk action you added. The nonce and capability are already checked.
subset_redirect_404_toolsactionarray $filtersPrint 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

HookTypeArgumentsWhat it does
subset_redirect_purge_urlsfilterstring[] $urls, array $redirectThe absolute URLs purged when a redirect is saved or deleted.
subset_redirect_purge_urlactionstring $urlFires for each purged URL. Use it to purge a host cache or CDN.
subset_redirect_page_cachesfilterstring[] $cachesThe 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

HookTypeArgumentsWhat it does
subset_redirect_settingsfilterarray $settingsPin a setting in code, whatever is saved. See SubsetRedirect\Settings::defaults() for the keys.
subset_redirect_capabilityfilterstring $capabilityThe capability needed to manage redirects, in the admin and over REST. Default manage_options.
subset_redirect_admin_tabsfilterarray $tabsAdd a tab to Subset → Redirects. Each tab has a label, a load callback and a render callback.
subset_redirect_redirect_form_rowsactionarray $valuesPrint extra rows at the end of the add/edit redirect form.
subset_redirect_list_filtersfilterarray $filtersRead and sanitize a custom filter for the redirects list.
subset_redirect_list_filter_controlsactionarray $filtersPrint a custom filter’s control.
subset_redirect_list_query_argsfilterstring[] $keysQuery arguments kept on links that show the same filtered list.
subset_redirect_search_clausesfilterarray $clauses, array $argsAdd SQL conditions to Redirects::search(), which the list, CSV export, REST and WP-CLI all use.
subset_redirect_docs_urlfilterstring $urlThe 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

HookTypeArgumentsWhat it does
subset_redirect_upgradeactionstring|false $installed, string $versionFires the first time a site runs a new version, including a fresh install. Make handlers safe to run twice.
subset_redirect_activateactionnoneFires on activation for each site set up.
subset_redirect_deactivateactionnoneFires on deactivation for each site.
subset_redirect_delete_data_on_uninstallfilterbool $deleteWhether 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:

ColumnValues
sourceThe URL to redirect from.
targetWhere to send visitors. Empty for a 410.
status_code301 (default), 302 or 410.
query_modeignore (default), exact or pass-through.
enabled1/0, yes/no or true/false. Defaults to enabled.
groupGroup name.
notesNotes.
externalWhether the target may be on another site. Same values as enabled.
match_typeexact (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.

RouteMethodsWhat it does
/redirectsGET, POSTList or create redirects.
/redirects/<id>GET, POST/PUT/PATCH, DELETERead, change or delete a redirect.
/redirects/testPOSTWhat a visit to url does. The same check as Test a URL.
/404sGETList logged 404s.
/404s/<id>GET, POST/PUT/PATCH, DELETERead 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:

NameTypeWhat it does
wildcard, regexmatch typesUse 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|nginxcommandPrint your redirects as Apache or nginx rules. Nothing is written to your server.
subset_redirect_pro_loadedactionFires once Pro has confirmed the free plugin is active.
subset_redirect_pro_batch_hitsfilterReturn true to batch hit statistics in a persistent object cache.
subset_redirect_pro_hit_daysfilterHow 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.