Skip to content
New site — Virtual Media Folders now has its own home.Visit vmf.soderlind.no →

Filters

Loupe Search exposes filters for changing what gets indexed, how it is searched and weighted, how results are returned and highlighted, and which searches Search insights counts, plus one action, loupe_search_searched. The quick reference lists them all.

Filters use the loupe_search_* prefix. The old wp_loupe_* names still work as deprecated aliases — see Renamed from WP Loupe.

  1. Where to put filter code
  2. Quick reference
  3. Indexing scope
  4. Index partitions
  5. Field content
  6. Schema
  7. Sortability
  8. Results
  9. Highlighting
  10. Search insights
  1. Settings page
  1. Recipes
  2. After changing a filter

Put these in a small mu-plugin (wp-content/mu-plugins/loupe-search-tweaks.php) rather than a theme’s functions.php. Indexing also runs from WP-CLI and from wp-cron, where the active theme may not be loaded — a filter that only exists in functions.php can therefore apply on the front end but silently not apply during a CLI reindex, producing an index that disagrees with your settings.

Filters that affect indexing must be registered before indexing runs, so register them at load time (not inside an init callback that runs late).

Filter Passed Use it to
loupe_search_post_types array $post_types Choose which post types are indexed
loupe_search_index_protected bool $should_index Index password-protected posts
loupe_search_indexable_post_statuses array $statuses, string $post_type Index extra publicly viewable statuses
loupe_search_is_indexable bool $indexable, WP_Post $post Veto individual posts from the index
loupe_search_db_path string $path Move the index directory
loupe_search_language string $language, string $locale Override the stemming language
loupe_search_stop_words array $words, array $languages Change the common words ignored in searches
loupe_search_partitions array $partitions, string $post_type Split a post type’s index, e.g. one per language
loupe_search_post_partition string $partition, WP_Post $post Choose the partition a post is indexed in
loupe_search_partition_language string $language, string $partition, string $post_type Set a partition’s stemming and stop-word language
loupe_search_query_partitions array $partitions, string $post_type Choose the partitions a search covers
loupe_search_partition_label string $label, string $partition, string $post_type Name a partition on the Dashboard
loupe_search_field_{$field_name} mixed $value Clean a core post field before indexing
loupe_search_schema_{$post_type} array $schema Add/remove fields, set weights and sorting
loupe_search_is_safely_sortable_{$post_type} bool $sortable, string $field_name Force a core field to be sortable
loupe_search_is_safely_sortable_meta_{$post_type} bool $sortable, string $field_name Correct meta-field sortability detection
loupe_search_posts_per_page int $per_page Change results per page
loupe_search_max_cacheable_query_length int $max_length Change which queries are written to the result cache
loupe_search_order_results array $hits, string $query, array $post_types, array $sort Reorder or regroup results merged across post types
loupe_search_advanced_hits array $hits, string $query, array $context Rerank or add hits in REST POST /search before pagination
loupe_search_highlight bool $enabled Turn match highlighting on for the default search
loupe_search_highlight_fields array $fields Choose which fields are highlighted
loupe_search_highlight_start_tag / _end_tag string $tag Change the tags wrapped around matches
loupe_search_highlight_crop_fields array $fields Choose which fields become cropped snippets
loupe_search_highlight_crop_length int $length Change snippet length (in words)
loupe_search_highlight_crop_marker string $marker Change the ellipsis on cropped snippets
loupe_search_insights_should_count bool $countable, string $source Decide whether a visitor search is counted by Search insights
loupe_search_settings_tabs array $tabs Add a tab to Settings → Loupe Search

Action: loupe_search_searched (string $query, int $total_hits, string $source) fires after a visitor search, before the Search insights checks — see Search insights.

Which post types are indexed. Defaults to the post types selected on the settings screen, falling back to [ 'post', 'page' ].

add_filter( 'loupe_search_post_types', function ( array $post_types ): array {
$post_types[] = 'book';
return $post_types;
} );

Append rather than replace unless you intend to override the settings screen — returning a hard-coded array makes the admin checkboxes have no effect.

Whether the current post should be indexed. The value passed in is empty( $post->post_password ), so password-protected posts arrive as false and everything else as true.

// Index password-protected posts too.
add_filter( 'loupe_search_index_protected', '__return_true' );

The filter receives no post object, so it cannot make a per-post decision — it is an on/off switch. Note that indexed protected posts become findable by their content, which is usually not what a password is for.

Post statuses that are indexed for a post type. Defaults to [ 'publish' ]. Applies when a post is saved, during a full or CLI reindex, and when front-end search results are loaded.

// Index closed bbPress topics, which stay publicly readable.
add_filter( 'loupe_search_indexable_post_statuses', function ( array $statuses, string $post_type ): array {
if ( 'topic' === $post_type ) {
$statuses[] = 'closed';
}
return $statuses;
}, 10, 2 );

Only add statuses that anonymous visitors can read. The REST API and abilities still return only publish posts to unauthenticated callers.

Final per-post veto, run after the post type, status and password checks pass. Return false to keep a post out of the index (an already indexed copy is removed on the next save). Returning true cannot re-admit a post that an earlier check rejected.

add_filter( 'loupe_search_is_indexable', function ( bool $indexable, WP_Post $post ): bool {
return $indexable && ! get_post_meta( $post->ID, 'noindex', true );
}, 10, 2 );

Excluded posts. Editors can exclude a single post without code: use the Search column, Quick Edit or the Exclude from search / Include in search bulk actions on the post list, or the Loupe Search panel in the editor sidebar. The flag is stored in the _loupe_search_exclude post meta and applied through this filter (priority 5), and the index is updated immediately. Exclusion only hides a post from search results — it is not access control; the post is still public at its URL.

Exclude by rule, e.g. everything in a category:

add_filter( 'loupe_search_is_indexable', function ( bool $indexable, WP_Post $post ): bool {
return $indexable && ! has_category( 'internal', $post );
}, 10, 2 );

Honour an SEO plugin’s noindex. Loupe Search does not read SEO plugin settings itself; opt in with a filter. Yoast SEO stores 1 in _yoast_wpseo_meta-robots-noindex, Rank Math stores noindex in the rank_math_robots array:

add_filter( 'loupe_search_is_indexable', function ( bool $indexable, WP_Post $post ): bool {
if ( ! $indexable ) {
return false;
}
if ( '1' === get_post_meta( $post->ID, '_yoast_wpseo_meta-robots-noindex', true ) ) {
return false;
}
return ! in_array( 'noindex', (array) get_post_meta( $post->ID, 'rank_math_robots', true ), true );
}, 10, 2 );

Run a reindex after adding or changing a rule so existing posts are re-evaluated.

When bbPress is active, Loupe Search uses this filter itself: forums, topics and replies are only indexed when their forum and all of its parent forums are public. When a forum is made private, hidden or public again, or a forum or topic is moved, the affected sub-forums, topics and replies are re-evaluated automatically.

Where the Loupe index files live. Defaults to WP_CONTENT_DIR . '/loupe-search-db'.

add_filter( 'loupe_search_db_path', function ( string $path ): string {
return WP_CONTENT_DIR . '/uploads/loupe-search-db';
} );

Use an absolute path that PHP can write to, and exclude it from version control. Changing this after indexing points the plugin at an empty directory — reindex afterwards.

The language Loupe uses for stemming and tokenization. By default it is derived from the site locale and mapped onto the stemmer’s language codes, so nb_NO and nn_NO become no, and pt_BR becomes pt. Loupe has stemmers for Catalan, Danish, Dutch, English, Finnish, French, German, Italian, Norwegian, Portuguese, Romanian, Russian, Spanish and Swedish; other languages are indexed without stemming.

add_filter( 'loupe_search_language', function ( string $language, string $locale ): string {
return 'sv_SE' === $locale ? 'sv' : $language;
}, 10, 2 );

The languages key of the loupe_search_advanced option takes precedence and can list several languages for multilingual content. Stems are stored when posts are indexed, so reindex after changing the language.

Common words such as “the”, “er” or “på” that are ignored in search queries, so they do not make every post match. They are still indexed, and a query made up only of stop words is searched as typed. The plugin bundles the Snowball stop word lists (BSD-3-Clause) for Danish, Dutch, English, Finnish, French, German, Italian, Norwegian, Portuguese, Russian, Spanish and Swedish, and uses the lists for the index languages. Words are lowercased, and spellings with diacritics are also added in ASCII form (“på” becomes “pa”), matching how Loupe folds query terms.

add_filter( 'loupe_search_stop_words', function ( array $words, array $languages ): array {
// Keep "ikke" (not) searchable, and ignore a site-specific word.
$words = array_diff( $words, [ 'ikke' ] );
$words[] = 'forum';
return $words;
}, 10, 2 );

Return an empty array to turn stop words off. The list is part of the index configuration, so reindex after changing it.

By default each post type has one index. Partitions split a post type’s index into several independent indexes, each with its own language, so stemming and stop words match the content. They are meant for add-ons such as Loupe Search Multilingual, which partitions by language; the five filters below work together.

  • Each partition is stored in a subdirectory of the post type’s index directory, for example loupe-search-db/post/nb/. Without partitions the layout is unchanged: loupe-search-db/post/.
  • A post is in exactly one partition. When a saved post moves to another partition (for example its language changes), it is removed from the old one.
  • A post type’s index is ready when every partition exists; the Dashboard shows a row per partition below the post type.
  • Reindex after changing the list of partitions or how posts are assigned. A full reindex removes partitions that are no longer in the list.

The partitions a post type’s index is split into. Names are lowercased and may contain only a-z, 0-9, - and _. Return [ '' ] (the default) for a single index.

add_filter( 'loupe_search_partitions', function ( array $partitions, string $post_type ): array {
return in_array( $post_type, [ 'post', 'page' ], true ) ? [ 'en', 'nb' ] : $partitions;
}, 10, 2 );

The partition a post is indexed in. The default is the first partition, which is also used when the filter returns a name that is not in the list.

add_filter( 'loupe_search_post_partition', function ( string $partition, WP_Post $post ): string {
return get_post_meta( $post->ID, 'language', true ) ?: $partition;
}, 10, 2 );

The language used for a partition’s stemming and stop words. The default is the site language (see loupe_search_language). The languages key of the loupe_search_advanced option, when set, overrides this for every partition.

add_filter( 'loupe_search_partition_language', function ( string $language, string $partition ): string {
return 'nb' === $partition ? 'no' : 'en';
}, 10, 2 );

The partitions a search covers. The default is all partitions. Unknown names are ignored; return an empty array to leave the post type out of the search. Search results are cached per set of partitions.

The filter also runs for post types that are not partitioned. Their only partition is '' (empty string), so keep it unless you want to leave them out.

add_filter( 'loupe_search_query_partitions', function ( array $partitions, string $post_type ): array {
$language = my_current_language();
// Unpartitioned post types have only the '' partition: keep searching them.
return in_array( $language, $partitions, true ) ? [ $language ] : $partitions;
}, 10, 2 );

The name shown for a partition on the Dashboard. The default is the partition name.

add_filter( 'loupe_search_partition_label', function ( string $label, string $partition ): string {
return [ 'en' => 'English', 'nb' => 'Norsk bokmål' ][ $partition ] ?? $label;
}, 10, 2 );

Transforms a field’s value just before it is indexed. {$field_name} is the field name, e.g. loupe_search_field_post_content.

// Strip HTML (including block comments) from post_content before indexing.
add_filter( 'loupe_search_field_post_content', 'wp_strip_all_tags' );

This only fires for properties that exist on the WP_Post object — post_content, post_title, post_excerpt, and so on. It does not fire for custom fields or taxonomy values, so loupe_search_field_my_meta_key will never run. To change how meta is indexed, use the schema filter.

Return a string or other scalar; returning an array will not index usefully.

The schema controls which fields are indexed and how they behave. The array you receive is the baseline schema merged with whatever is configured on the settings screen, so read before you write.

Each field accepts:

Key Type Default Meaning
weight float 1.0 Relevance multiplier in search results
indexable bool false Include the field in the index
filterable bool false Allow filtering and terms facets on the field
sortable bool false Allow sorting by the field
sort_direction string 'desc' Default direction, 'asc' or 'desc'

sortable is also gated by the sortability checks below — setting it to true on a field that holds arrays will be overridden.

add_filter( 'loupe_search_schema_book', function ( array $schema ): array {
// Add a custom field.
$schema['book_isbn'] = [
'weight' => 2.0,
'indexable' => true,
'filterable' => true,
];
// Make books sort by publication date, newest first.
$schema['book_published'] = [
'weight' => 1.0,
'indexable' => true,
'sortable' => true,
'sort_direction' => 'desc',
];
// Boost titles for this post type.
$schema['post_title']['weight'] = 3.0;
// Stop indexing excerpts.
unset( $schema['post_excerpt'] );
return $schema;
} );

Only post_date is present before settings are applied:

[
'post_date' => [
'weight' => 1.0,
'indexable' => true,
'filterable' => true,
'sortable' => true,
'sort_direction' => 'desc',
],
]

Every other field — post_title, post_content, post_excerpt, post_author, permalink, and any custom fields — is added from the settings screen. Do not assume a field exists in $schema; check first when modifying:

add_filter( 'loupe_search_schema_post', function ( array $schema ): array {
if ( isset( $schema['post_title'] ) ) {
$schema['post_title']['weight'] = 4.0;
}
return $schema;
} );

Before a field is registered as sortable, the plugin checks that its values are scalar — Loupe cannot sort on arrays. These two filters let you override that verdict.

loupe_search_is_safely_sortable_{$post_type}

Section titled “loupe_search_is_safely_sortable_{$post_type}”

Runs for core post fields that are not already classified as sortable or non-sortable. Receives false by default plus the field name.

add_filter( 'loupe_search_is_safely_sortable_book', function ( bool $sortable, string $field_name ): bool {
return 'menu_order' === $field_name ? true : $sortable;
}, 10, 2 );

loupe_search_is_safely_sortable_meta_{$post_type}

Section titled “loupe_search_is_safely_sortable_meta_{$post_type}”

Runs for meta fields. The incoming value comes from sampling the meta value of up to five posts: true if all sampled values were scalar (or geo-points).

That sample can be wrong. If only the sixth post stores an array, the field is wrongly marked sortable and sorting misbehaves; if the first five posts have no value, a perfectly sortable field is marked unsortable. Use this filter to state the answer explicitly:

add_filter( 'loupe_search_is_safely_sortable_meta_book', function ( bool $sortable, string $field_name ): bool {
// This one is always a single number, regardless of what sampling found.
if ( 'book_price' === $field_name ) {
return true;
}
// This one sometimes holds an array — never sort on it.
if ( 'book_contributors' === $field_name ) {
return false;
}
return $sortable;
}, 10, 2 );

Number of results per page for front-end searches. Defaults to the query’s posts_per_page, falling back to Settings → Reading → “Blog pages show at most”.

add_filter( 'loupe_search_posts_per_page', function ( int $per_page ): int {
return 20;
} );

This affects the WordPress search loop only. The REST API takes its page size from the request — see Search API.

Maximum query length, in bytes, that is written to the result cache. Defaults to 128. Longer queries still run, they are just not cached.

Search is reachable without authentication, so every distinct query would otherwise be able to create a transient. The bound keeps a visitor from filling the options table with long throwaway queries.

add_filter( 'loupe_search_max_cacheable_query_length', function ( int $max_length ): int {
return 256;
} );

Return 0 to disable result caching entirely.

Reorders the combined result set after hits from every post-type index are merged. Each post type has its own index, so the engine searches them in turn; by default the merged hits are sorted by relevance score (descending) so a more relevant page can outrank a less relevant post instead of every post type being grouped together.

Each $hit is an array carrying at least id, _score, and post_type. Return the array reordered to apply a different policy.

// Keep pages above posts, most relevant first within each group.
add_filter( 'loupe_search_order_results', function ( array $hits, string $query ): array {
$rank = [ 'page' => 0, 'post' => 1 ];
usort( $hits, function ( $a, $b ) use ( $rank ) {
return [ $rank[ $a['post_type'] ] ?? 9, -$a['_score'] ]
<=> [ $rank[ $b['post_type'] ] ?? 9, -$b['_score'] ];
} );
return $hits;
}, 10, 2 );

Scores from separate indexes are only approximately comparable, so the default relevance merge is a heuristic; use this filter when a site needs a stricter or different ordering.

Since 1.5.0 the filter also receives the searched post types and the applied field sort (a list of field/direction pairs, empty when sorted by relevance). Hits returned for a post that is not in the index are shown like any other result, provided the post is a published post of a searched type.

Since 1.5.0. Filters the merged and sorted hits of REST POST /search before pagination, so an add-on can rerank them or add hits from another retriever (Loupe Semantic Search uses it for hybrid search). Each hit is an array with at least id, post_type and _score. Added hits of a post type that was not searched are dropped, every hit still passes the public-visibility check, and totalHits is raised by the number of hits added.

$context holds:

Key Type Description
post_types string[] Post types searched
filter string Loupe filter string built from the request ('' when none)
sort string[] Loupe sort strings
payload array The request payload
limit int Hits needed for the requested page (offset + page size)
matches_filter callable Takes post IDs, returns those whose indexed documents match the request’s filter

Use matches_filter before adding a hit, so added hits respect the request’s filters. It runs a filtered search, which Loupe caps at 1000 matches.

add_filter( 'loupe_search_advanced_hits', function ( array $hits, string $query, array $context ): array {
$extra = my_retriever( $query, $context['post_types'] ); // [ [ 'id' => 12, 'post_type' => 'post', '_score' => 0.4 ], … ]
$ok = array_flip( ( $context['matches_filter'] )( array_column( $extra, 'id' ) ) );
foreach ( $extra as $hit ) {
if ( isset( $ok[ $hit['id'] ] ) && ! in_array( $hit['id'], array_column( $hits, 'id' ), true ) ) {
$hits[] = $hit;
}
}
return $hits;
}, 10, 3 );

loupe_search_is_post_indexable() (function)

Section titled “loupe_search_is_post_indexable() (function)”

Since 1.5.0. loupe_search_is_post_indexable( WP_Post|int $post ): bool tells whether Loupe Search indexes a post: indexed post type, indexable status, password protection and the loupe_search_is_indexable filter (which covers posts excluded from search). Add-ons that keep their own index can use it to index exactly the same posts. Returns false until Loupe Search has loaded.

By default the WordPress search results page shows plain titles and excerpts. Turn on the Highlight Matches checkbox (Settings → Loupe Search → Search Behavior), or use these filters, to opt the default search loop into match highlighting: matched terms are wrapped in a tag (default <mark>) and the excerpt becomes a cropped snippet built around the match. The matches come from Loupe, so a typo-corrected query still highlights the term it actually matched.

Highlighting is a rendering concern only — it needs no reindex and does not change what is stored. The REST API has its own per-request highlighting; see Search API.

The master switch. It defaults to the Highlight Matches checkbox on Settings → Loupe Search → Search Behavior (off out of the box). Use this filter to force it on or off in code regardless of the setting:

add_filter( 'loupe_search_highlight', '__return_true' );

Nothing else here has any effect until this resolves to true.

Which fields get matched terms wrapped in tags. Defaults to [ 'post_title', 'post_content' ]. A field is only highlighted if it is indexable for that post type; unknown names are ignored.

add_filter( 'loupe_search_highlight_fields', function ( array $fields ): array {
return [ 'post_title' ]; // Highlight titles only.
} );

loupe_search_highlight_start_tag / loupe_search_highlight_end_tag

Section titled “loupe_search_highlight_start_tag / loupe_search_highlight_end_tag”

The markup wrapped around each match. Default <mark> / </mark>. Tags are sanitized to a safe inline allowlist (mark, em, strong, span, b, i, each allowing class), so script-capable markup can never be injected.

add_filter( 'loupe_search_highlight_start_tag', fn() => '<span class="hit">' );
add_filter( 'loupe_search_highlight_end_tag', fn() => '</span>' );

If a theme wraps get_the_title() in esc_html(), the tags will show as literal text on that theme — highlight titles via the_title there instead.

Which fields are returned as a cropped snippet centered on the match, instead of the full field. Defaults to [ 'post_content' ], which is what turns the search excerpt into a snippet. Pass an empty array to keep full (still highlighted) fields.

add_filter( 'loupe_search_highlight_crop_fields', '__return_empty_array' );

Snippet length in words. Default 55.

add_filter( 'loupe_search_highlight_crop_length', fn() => 30 );

The marker placed where text is trimmed. Default ….

add_filter( 'loupe_search_highlight_crop_marker', fn() => ' [&hellip;]' );

Search insights (Settings → Loupe Search → Search insights) is off by default; its report is under Dashboard → Search insights. When on, it stores daily totals per normalized query — searches, zero-result searches and total results — and nothing about the visitor. Searches are counted from the WordPress search page (first page only) and from REST requests that send countSearch: true. Admin screens, WP-CLI, cron, users who can manage_options and obvious bots are skipped; queries longer than 100 characters or that look like an email address or phone number are discarded.

Final say on whether the current search is counted. $source is main (the WordPress search page) or rest.

// Don't count searches from logged-in users.
add_filter( 'loupe_search_insights_should_count', function ( bool $countable, string $source ): bool {
return $countable && ! is_user_logged_in();
}, 10, 2 );

Fires after a visitor search, with the query as typed, the total number of hits and the source (main or rest). On the search page it fires for the first results page of the main query; over REST only when the client sends countSearch: true. It fires before the insights checks above, so searches rejected by loupe_search_insights_should_count still trigger it. Use it to feed your own analytics; never store personal data from the request.

add_action( 'loupe_search_searched', function ( string $query, int $total_hits, string $source ): void {
if ( 0 === $total_hits ) {
do_action( 'my_analytics_event', 'search_no_results' );
}
}, 10, 3 );

Since 1.5.0. Adds tabs to Settings → Loupe Search, after the built-in ones. Each tab is keyed by its slug (?page=loupe-search&tab=<slug>) and needs a label and a render callback that prints the tab body. The built-in slugs (dashboard, fields, search-behavior, insights) cannot be replaced, and tabs without a label or a callable render are ignored.

A form in the tab can post to options.php with its own settings group; WordPress returns to the same tab after saving. Check capabilities in your own handlers: the page itself requires manage_options.

add_filter( 'loupe_search_settings_tabs', function ( array $tabs ): array {
$tabs['my-addon'] = [
'label' => __( 'My add-on', 'my-addon' ),
'render' => 'my_addon_render_settings',
];
return $tabs;
} );

Index a custom post type with its custom fields

Section titled “Index a custom post type with its custom fields”
add_filter( 'loupe_search_post_types', function ( array $post_types ): array {
$post_types[] = 'recipe';
return $post_types;
} );
add_filter( 'loupe_search_schema_recipe', function ( array $schema ): array {
$schema['recipe_ingredients'] = [
'weight' => 2.0,
'indexable' => true,
'filterable' => true,
];
$schema['recipe_time'] = [
'weight' => 1.0,
'indexable' => true,
'filterable' => true,
'sortable' => true,
'sort_direction' => 'asc',
];
return $schema;
} );
add_filter( 'loupe_search_is_safely_sortable_meta_recipe', function ( bool $sortable, string $field_name ): bool {
return 'recipe_time' === $field_name ? true : $sortable;
}, 10, 2 );

Strip shortcodes as well as HTML from indexed content

Section titled “Strip shortcodes as well as HTML from indexed content”
add_filter( 'loupe_search_field_post_content', function ( $value ) {
return wp_strip_all_tags( strip_shortcodes( (string) $value ) );
} );

Keep a post type out of the index temporarily

Section titled “Keep a post type out of the index temporarily”
add_filter( 'loupe_search_post_types', function ( array $post_types ): array {
return array_values( array_diff( $post_types, [ 'page' ] ) );
} );

Highlight matches on the default search results

Section titled “Highlight matches on the default search results”
// Turn it on, wrap matches in a styled span, and keep excerpts short.
add_filter( 'loupe_search_highlight', '__return_true' );
add_filter( 'loupe_search_highlight_start_tag', fn() => '<mark class="loupe-hit">' );
add_filter( 'loupe_search_highlight_end_tag', fn() => '</mark>' );
add_filter( 'loupe_search_highlight_crop_length', fn() => 40 );

Filters that affect what or how content is indexed — post types, schema, field content, sortability, protected posts, partitions — only take effect for content indexed afterwards. Reindex so the existing index matches:

Terminal window
wp loupe-search reindex

Filters that only affect reading, such as loupe_search_posts_per_page and the loupe_search_highlight* filters, take effect immediately.