Skip to content

[00] Subset Search, For developers

Developer reference

Subset Search's PHP functions, actions and filters, wp-config.php constants, WP-CLI commands and REST API routes.

This page lists everything you can use to work with Subset Search from code: the PHP functions, hooks, constants, WP-CLI commands and REST API. Every hook name starts with subset_search_.

How a search is answered

Subset Search hooks posts_pre_query. When a query is one it answers, the search is parsed, scored against the index in one SQL statement, and the best candidates go into a second WP_Query with post__in. That second query carries every argument the original had except s, so WordPress’s visibility rules and other plugins’ pre_get_posts filters still apply. The original query gets the page of posts and the total back.

It answers the main search query, a WP_Query with 'subset_search' => true, and the REST API’s post routes with ?search=. Admin list screens are answered only when Admin search is on. A request that isn’t a search runs no extra queries.

The results are on the query as $wp_query->get( 'subset_search_results' ), a Subset\Search\Query\Results.

Functions

Search from PHP

subset_search() runs a search without a WP_Query, for a theme or plugin that builds its own results. It ranks like the site’s search and shows what the current user may see.

<?php
$results = subset_search( 'opening hours', array(
	'post_type' => array( 'page' ), // Default: every indexed type.
	'per_page'  => 10,              // At most 100.
	'page'      => 1,
	'orderby'   => 'relevance',     // Or date, title, menu_order.
) );

foreach ( $results->ids as $id ) {
	printf( '<p>%s (%.2f)</p>', esc_html( get_the_title( $id ) ), $results->scores()[ $id ] );
}

Results has ids (this page’s post IDs, best first), scores() (post ID to score), total, pages, page, per_page, suggestion (a corrected search, or null) and query, the parsed search.

Place the did-you-mean line

subset_search_did_you_mean() returns, and by default prints, the line for above the main search’s results: “Did you mean booking?” linked to that search, or a note that a quoted phrase matched nothing exactly. It’s empty when there’s nothing to say. The plugin already prints it where the results start, so remove that first if you place it yourself:

<?php
remove_action( 'subset_search_did_you_mean_output', array( Subset\Search\Plugin::instance()->suggestion(), 'output' ) );

// In your search template:
subset_search_did_you_mean();

Find posts like a slug

Subset\Search\Api::match_slug() returns published posts that may be what a slug was looking for, such as the last segment of a 404’s URL. Subset Redirects Pro uses it for its suggested redirects. Check class_exists( Subset\Search\Api::class ) before calling it.

The slug’s words are searched for with OR, so any one word finds a post. It covers every language and every indexed public post type with its own pages, whoever’s logged in. Each result has id, slug, title, score, and a slug_similarity and title_similarity from 0 to 1. Results come most alike first, at most $limit (up to 20).

<?php
foreach ( Subset\Search\Api::match_slug( 'opening-hours', 20 ) as $match ) {
	if ( max( $match['slug_similarity'], $match['title_similarity'] ) >= 0.6 ) {
		$target = get_permalink( $match['id'] );
		break;
	}
}

Subset\Search\Api::similarity( $a, $b ) scores two slugs the same way, from 0 to 1. Reordered words still count as alike.

Indexing

HookTypeArgumentsNotes
subset_search_post_typesfilterlist<string> $typesThe post types indexed. Types excluded from search are dropped after this.
subset_search_index_postfilterbool $index, WP_Post $postWhether a post is indexed. Return false to keep it out; one already indexed is removed the next time it’s indexed.
subset_search_documentfilterarray $fields, WP_Post $postThe post’s text by field before it’s tokenised: title, content, excerpt, taxonomy, meta, comment, author, file. Add text to a field to index it.
subset_search_custom_fieldsfilterlist<string> $keys, WP_Post $postThe meta keys indexed for a post, where % is a wildcard. Default: the Custom fields setting.
subset_search_index_taxonomyfilterbool $index, string $taxonomyWhether a taxonomy’s term names are indexed when the Taxonomies setting lists none. Default: whether it’s public.
subset_search_post_languagefilterstring $lang, WP_Post $postThe post’s language code, stored in the index. Set by the Polylang and WPML integrations.
subset_search_tokensfilterarray $tokens, string $field, WP_Post $postA field’s terms (term to count) before they’re written.
subset_search_stopwordsfilterlist<string> $words, string $localeThe stopwords, compared after lowercasing and accent folding.
subset_search_stemfilter?callable $stemmer, string $localeTakes a term and returns its stem, or null for no stemming. Default: the Porter stemmer on English locales.
subset_search_indexedactionint $post_id, array $statsAfter a post’s index rows are written. $stats holds terms (distinct) and length (total).
subset_search_reindex_completeactionarray $jobWhen a full rebuild finishes: scope, post_types, total, done, started_at, errors and failed.

A filter that changes what’s indexed only reaches posts as they’re indexed again. Run wp subset search index --all after adding one.

<?php
// Index each event's venue with its custom fields.
add_filter( 'subset_search_document', function ( array $fields, WP_Post $post ): array {
	if ( 'event' === $post->post_type ) {
		$fields['meta'] = trim( ( $fields['meta'] ?? '' ) . "\n" . get_post_meta( $post->ID, 'venue', true ) );
	}
	return $fields;
}, 10, 2 );

Searching

HookTypeArgumentsNotes
subset_search_do_queryfilterbool $take_over, WP_Query $wp_queryWhether Subset Search answers a query. When it doesn’t, WordPress’s own search runs.
subset_search_queryfilterQuery $query, ?WP_Query $wp_queryThe parsed search before it runs: term groups, exclusions, phrases, post types, statuses and language. $wp_query is null for a search run directly.
subset_search_languagefilter?string $lang, ?WP_Query $wp_queryThe language searched, or null for every language.
subset_search_synonymsfilterarray $synonymsWord to the words that also satisfy it, one way.
subset_search_weightsfilterarray $weightsField to weight.
subset_search_post_type_weightsfilterarray $weightsPost type to weight. Missing types weigh 1.
subset_search_max_candidatesfilterint $max, Query $queryHow many results a search scores. Only these are pageable. Default 1,000.
subset_search_scoresfilterarray $scores, Query $queryPost ID to score, before they’re ordered.
subset_search_query_argsfilterarray $args, ?WP_Query $wp_queryThe second WP_Query’s arguments, with post__in the candidates best first.
subset_search_resultsfilterResults $results, WP_Query $wp_queryA taken-over query’s results before WordPress shows them.
subset_search_conflictsfilterarray $foundThe other search plugins Subset Search stands aside for, slug to name. Return an empty array to answer searches alongside them. Add it from a plugin, not a theme.
<?php
// Let a custom loop use the index.
$query = new WP_Query( array(
	's'             => 'opening hours',
	'post_type'     => 'page',
	'subset_search' => true,
) );

Results and output

HookTypeArgumentsNotes
subset_search_excerptfilterstring $excerpt, WP_Post $post, Results $resultsA result’s highlighted excerpt: escaped text with the matched words marked.
subset_search_highlight_tagfilterstring $tagThe element a matched word is wrapped in, with the class subset-search-hit. Default mark.
subset_search_did_you_meanfilter?string $suggestion, Results $resultsThe search offered as “Did you mean”. null for none.
subset_search_did_you_mean_outputactionResults $resultsFires above the main search’s results, where the plugin prints “Did you mean”.

Search log

HookTypeArgumentsNotes
subset_search_log_queryfilterbool $log, Query $query, int $hitsWhether to log a search. Default true.
subset_search_log_row_actionsfilterarray $actions, array $itemThe links under a search on the Searches tab: action to link HTML.

Settings and admin

HookTypeArgumentsNotes
subset_search_capabilityfilterstring $capabilityWho manages Subset Search: its settings, index, log and Tester. Default manage_options.
subset_search_settings_defaultsfilterarray $defaultsEvery setting and its default. An add-on adds its own keys here.
subset_search_sanitize_settingsfilterarray $clean, array $inputThe cleaned settings. Clean your own keys from $input.
subset_search_settingsfilterarray $settingsThe settings after they’re read. Settings pinned by a constant are applied after this.
subset_search_admin_tabsfilterarray $tabsThe screen’s tabs, slug to label.
subset_search_admin_tab_{slug}actionPrints an added tab.
subset_search_settings_after_formactionstring $tabAfter a settings tab’s form: search, index or searches.
subset_search_import_sourcesfilterlist<Source> $sourcesThe plugins Subset Search can import from. Add a Subset\Search\Import\Source subclass.

Loading, install and uninstall

HookTypeArgumentsNotes
subset_search_loadingactionPlugin $pluginBefore any component registers. An add-on adds its components here.
subset_search_bootedactionBootstrap $bootstrapAfter every component has registered.
subset_search_activateactionOn activation, on each site. Starts the first index.
subset_search_deactivateactionOn deactivation, on each site.
subset_search_upgradeactionstring|false $from, string $toAfter an update, with the version before and after.
subset_search_delete_data_on_uninstallfilterbool $deleteWhether deleting the plugin deletes this site’s data. Default true. Add it from a must-use plugin.
subset_search_client_ipfilterstring $ipThe client IP the REST search route’s rate limit counts, from REMOTE_ADDR. Return a proxy’s header here if you trust it.
subset_search_lock_waitfilterfloat $seconds, string $nameHow long a request waits for the index lock.
subset_search_lock_ttlfilterint $seconds, string $nameHow long a held lock lasts if its request dies.
subset_search_lock_use_object_cachefilterbool $use, string $nameWhether locks use the object cache rather than the options table.

Constants

Every setting can be pinned in wp-config.php with SUBSET_SEARCH_ and the setting’s name in capitals. A pinned setting shows as locked on the settings screen, and wp subset search settings list shows its source as constant.

<?php
define( 'SUBSET_SEARCH_LOG', false );                       // Turn the search log off.
define( 'SUBSET_SEARCH_ADMIN_SEARCH', true );               // Rank admin list screen searches.
define( 'SUBSET_SEARCH_DELETE_DATA_ON_UNINSTALL', false );  // Keep the data when the plugin is deleted.

wp subset search settings list prints every setting’s name.

WP-CLI

Every command is under wp subset search. Run wp help subset search <command> for its options.

CommandWhat it does
wp subset search index [<id>...] [--all] [--post-type=<type>] [--force]Indexes posts. --all rebuilds the whole index with a progress bar, the same job Rebuild index starts.
wp subset search index statusPosts indexed against indexable, the index’s size and the last rebuild.
wp subset search index clear [--yes]Empties the index. Searches go to WordPress until it’s rebuilt.
wp subset search query <text> [--explain]Runs a search as a logged-out visitor and prints the results. --explain adds what the Tester shows. Not logged.
wp subset search settings list|get|set|resetReads and changes the settings, cleaned as the settings screen cleans them.
wp subset search stopwords list|add|remove|resetReads and changes the stopwords. A change needs a rebuild.
wp subset search synonyms list|add|removeReads and changes the synonyms.
wp subset search log list|top|prune|clearReads, prunes and clears the search log. list --view=zero lists searches that found nothing.
wp subset search import [<source>] [--dry-run] [--log] [--overwrite]Imports from another search plugin. Without a source, lists the plugins with data on the site.
wp subset search query "opening hours" --explain
wp subset search log list --view=zero --days=7 --format=csv > zero.csv

REST API

Every route is under /wp-json/subset-search/v1. Only GET /search is public. The rest need the plugin’s capability, through a logged-in cookie with an X-WP-Nonce header or an application password.

RouteWhat it does
GET /searchSearches, as a logged-out visitor sees the site, or as the logged-in caller when the request carries a REST nonce.
GET /indexThe running rebuild, the last one, and whether a settings change needs one.
POST /index/rebuildStarts a rebuild. post_types limits it to some types.
POST /index/stepCarries a running rebuild on for a few seconds.
DELETE /indexStops a rebuild. What it indexed stays.
POST /testWhat the Tester shows for q, and optionally post_type. Not logged.
GET or PUT /stopwordsThe stopwords as { words, bundled, reindex_needed }. PUT takes words, and an empty list goes back to the list for the site language.
GET or PUT /synonymsThe synonyms as { synonyms }. PUT takes synonyms.
GET /logA page of logged searches: view (all, results or zero), days, search, page and per_page.
GET /log/top, GET /log/zeroThe most searched queries, and the most searched that found nothing: days (30) and limit (20).
DELETE /logClears the log.

A list or setting pinned in wp-config.php can’t be changed, and PUT answers 409.

ParameterDefault
qWhat to search for. Required.
post_typeEvery indexed typeOne type, or a list.
per_page10At most 50.
page1
orderbyrelevanceOr date, title, menu_order.
{
  "total": 2,
  "pages": 1,
  "suggestion": null,
  "results": [
    {
      "id": 42,
      "type": "page",
      "title": "Opening hours",
      "url": "https://example.com/opening-hours/",
      "excerpt": "Our <mark class=\"subset-search-hit\">opening</mark> <mark class=\"subset-search-hit\">hours</mark> change in winter.",
      "date": "2026-01-01T09:00:00+00:00",
      "score": 6.1204
    }
  ]
}

The totals are also in the X-WP-Total and X-WP-TotalPages headers. title is plain text and excerpt is escaped HTML. A client may make 60 searches a minute. Past that, the route answers 429 with a Retry-After header. Change the limit with subset_search_rest_rate_limit, which takes 0 for no limit.

HookTypeArgumentsNotes
subset_search_rest_rate_limitfilterint $limitSearches a client may make a minute. Default 60.
subset_search_rest_search_argsfilterarray $args, WP_REST_Request $requestThe search’s post_type, per_page, page and orderby before it runs.
subset_search_rest_resultfilterarray $item, WP_Post $postOne result before it’s returned.

Searches through this route are logged on the Searches tab, from their first page only.