Use Relevanssi functions with the correct arguments and output
Functions
Relevanssi provides functions for running searches, displaying prepared results, processing text, and maintaining the index. This reference shows their parameters and defaults, distinguishes returned values from printed output, and identifies calls that change stored data.
Use these functions after WordPress and Relevanssi have loaded, from a site plugin, child theme, or template. Check availability before calling them so deactivating Relevanssi does not cause an undefined-function error. Functions in the shared library are used in Free and Premium; the spelling-dictionary update below is Premium-only. Special result types and multilingual behaviour depend on the corresponding features and integrations.
Run a search explicitly
For a secondary query, the usual approach is new WP_Query() with relevanssi => true. To use relevanssi_do_query() directly without running an initial database query, create an empty query object and parse its arguments first:
if ( function_exists( 'relevanssi_do_query' ) ) {
$query = new WP_Query();
$query->parse_query(
array(
's' => 'orchard cobalt',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 20,
)
);
$posts = relevanssi_do_query( $query );
// Inspect $query->posts, found_posts, and max_num_pages.
}
The function updates the query object and returns the current page of results. It can also generate excerpts and write a search-log entry according to settings; it is not merely a raw SQL lookup. A direct call does not pass through the automatic query wrapper’s relevanssi_modify_wp_query hook, so set the required restrictions on the object yourself. See Complex queries for filtering examples.
Display output versus returned values
Do not assume every function with a similar name behaves like its WordPress counterpart. relevanssi_get_the_tags() returns a formatted HTML string, not an array of terms. relevanssi_search_form() returns the form HTML. Use an explicit echo when displaying its result:
if ( function_exists( 'relevanssi_search_form' ) ) {
echo relevanssi_search_form( array( 'post_type' => 'post' ) );
}
Title helpers use post_highlighted_title when it has been prepared, and otherwise fall back to the original title. They do not generate highlighting just by reading the title. relevanssi_the_excerpt() prints the current object’s existing excerpt; use relevanssi_do_excerpt() to generate an excerpt yourself.
Returned titles, snippets, tag lists, and highlighted strings can contain markup. Choose output handling that fits the context: escape a plain string, use esc_url() for a returned URL, or preserve only appropriate HTML with wp_kses_post(). Do not escape intended highlighting as plain text if you want it to render.
Detailed function guides
- relevanssi_count_term_occurrances()
- relevanssi_didyoumean()
- relevanssi_do_query()
- relevanssi_get_permalink()
- relevanssi_get_post_meta_for_all_posts()
- relevanssi_get_the_tags()
- relevanssi_get_the_title()
- relevanssi_highlight_terms()
- relevanssi_index_doc()
- relevanssi_the_excerpt()
- relevanssi_the_permalink()
- relevanssi_the_tags()
- relevanssi_the_title()
- relevanssi_update_words_option()
Function reference
The signatures below show optional arguments and their defaults. Pass the kinds of values described for each function; this is a usage reference rather than a list of PHP type declarations. Some helpers rely on the current Loop, query, or already prepared Relevanssi result data.
relevanssi_add_apostrophes($str)
Returns the input surrounded by single quotes. It does not escape the input for SQL or HTML.
relevanssi_add_quotes($str)
Returns the input surrounded by double quotes. It does not escape the input for SQL or HTML.
relevanssi_add_synonyms($query)
Returns the query with synonyms from the current language's configured synonym list added. It does not itself execute a search.
relevanssi_build_index($extend_offset = false, $verbose = null, $post_limit = null, $is_ajax = false)
Builds the index using saved indexing rules. The default false $extend_offset clears the existing index first; true extends without clearing, and a numeric offset continues from that position. $verbose is retained for compatibility and is no longer used. $post_limit limits the batch. Returns completion and indexed-post counts; Ajax context uses named keys. Changes stored data.
relevanssi_count_term_occurrances($query, $mode = 'array')
Sums stored occurrences of each space-separated term across the Relevanssi index. The default returns a term-to-count array; mode 'string' returns formatted HTML. These are occurrences, not the number of matching posts. Keep the function name's historical spelling.
relevanssi_debug_echo($notice)
Writes a diagnostic message with WP_CLI::log() in WP-CLI. Otherwise it uses error_log() when background debugging is enabled, or echoes escaped text. The output destination depends on the execution context and settings.
relevanssi_didyoumean($query, $pre, $post, $n = 5, $echoed = true)
Generates Did you mean suggestion HTML using the available Free or Premium implementation. Supply the search query and markup before and after the suggestion. The threshold $n controls when suggestions are shown. It echoes by default and also returns the result, which can be null when no suggestion is available; set $echoed to false to obtain it without printing.
relevanssi_do_excerpt($t_post, $query, $excerpt_length = null, $excerpt_type = null)
Returns a generated excerpt for the supplied post object and query. Omitted length and type use the saved settings. Explicit types are 'words' or 'chars'. Does not print the excerpt.
relevanssi_do_query(&$query)
Runs Relevanssi on a WP_Query object passed by reference. Set its 's' and other arguments first. Updates posts, post_count, found_posts, and pagination, and returns the page of results. Normal output uses post objects; the fields argument can change the result format.
relevanssi_do_shortcode($content)
Returns content with shortcodes expanded when expansion is enabled, or with shortcode markup stripped when it is disabled. Expansion uses Relevanssi's shortcode handling and restores an existing global post after processing.
relevanssi_flatten_array($arr)
Recursively collects nested array values into one space-separated string. It returns a string, not a flattened array.
relevanssi_from_and_to($request, $from)
Returns 'from' and 'to' dates in Y-m-d format from a request array and a default starting date. Recognises direct from/to values and ranges including this_year, this_month, last_month, this_week, last_week, last_30, and last_7.
relevanssi_generate_missing_terms_list($post)
Returns the Missing search-terms HTML from prepared relevanssi_hits['missing_terms'] data on a result object. It does not run a new search to discover missing terms.
relevanssi_get_an_object($source)
Returns an array with 'object' and 'format' keys. Converts a post ID or a supported Relevanssi result identifier/object into the underlying object while recording the input format. Check the object for errors or a missing result before using it.
relevanssi_get_attachment_suffix($post)
Returns the attachment's filename suffix derived from its guid. Accepts an attachment object or ID. Returns an empty string for a non-attachment or an ID that cannot be fetched. This is not MIME-type detection.
relevanssi_get_current_language($locale = true)
Returns a locale by default, or a language code when $locale is false. Uses the site locale and, when present, the relevant WPML or Polylang context for the current post or term.
relevanssi_get_permalink($post = 0)
Returns the post's permalink through the relevanssi_permalink filter. Accepts a post ID or object; the default uses the current post. Search highlighting parameters depend on the active filters and settings.
relevanssi_get_post($post_id, $blog_id = -1)
Fetches a post using Relevanssi's object cache; the optional blog ID defaults to the current site. Returns a WP_Error when an ordinary post cannot be found. Premium supports additional internal result identifiers; these are not interchangeable with ordinary WordPress post IDs.
relevanssi_get_post_meta_for_all_posts($post_ids, $field)
Returns an array keyed by post ID containing raw stored values for one metadata key. Supply an array of validated integer post IDs. Values are not automatically unserialized; multiple values for the same key are not returned as a separate list.
relevanssi_get_post_object($post_id)
Resolves an ordinary post ID through relevanssi_get_post(), or a **type**id identifier such as **user**123 or **category**123 to the corresponding object. Results can include a post, term, user, error, or missing value, so check before accessing properties.
relevanssi_get_post_status($post_id)
Returns a post's status through Relevanssi's cached post lookup. Supply the intended post ID.
relevanssi_get_post_type($post_id)
Returns a post's type through Relevanssi's cached post lookup. Supply the intended post ID.
relevanssi_get_term_tax_id($term_id, $taxonomy)
Looks up the term_taxonomy_id for a term ID and taxonomy. This ID is distinct from term_id. A missing combination can return null.
relevanssi_get_the_title($post)
Returns a supplied post object's prepared post_highlighted_title, falling back to post_title. Also accepts a post ID. Returns an empty string when fetching the ID produces a WP_Error. The $post argument is required.
relevanssi_highlight_terms($content, $query, $convert_entities = false)
Returns content with matching query terms highlighted according to Relevanssi settings. $convert_entities controls entity conversion. It does not change the post in the database.
relevanssi_index_doc($index_post, $remove_first = false, $custom_fields = '', $bypass_global_post = false, $debug = false)
Indexes one post ID or post object. $remove_first replaces existing entries when true; $bypass_global_post ensures the supplied post is used. $custom_fields supplies the field selection, and $debug enables diagnostic output. Returns an insert-query count or a failure/exclusion value; this is not a count of matched search results. Changes the stored index.
relevanssi_launch_ajax_action($action, $payload_args = array())
Sends a non-blocking wp_remote_post() to WordPress's admin-ajax.php for the requested action, adding its nonce. Returns the HTTP API response or WP_Error, not the eventual action's completed result. Triggers a request and any writes performed by that action.
relevanssi_mb_strcasecmp($str1, $str2, $encoding = '')
Returns a multibyte-aware, case-insensitive natural string comparison. A zero result means equal; negative and positive values indicate ordering. The optional encoding defaults to an empty string.
relevanssi_mb_trim($str)
Returns the string with supported surrounding whitespace, non-breaking spaces, and null bytes trimmed.
relevanssi_remove_doc($post_id, $keep_internal_links = false)
Removes a post's entries from the Relevanssi index. $keep_internal_links preserves internal-link indexing when true. Changes stored data; it does not delete the WordPress post.
relevanssi_remove_quotes($str)
Returns the string with supported straight and curly double quotation marks removed. It does not remove every possible quote character or apostrophe.
relevanssi_return_id_parent($post_object)
For an ordinary post result, returns a small object with ID and post_parent. For a term result, returns its term ID and a parent value of zero. Use the appropriate result-object shape rather than assuming every WordPress object has post-like properties.
relevanssi_return_id_type($post_object)
For ordinary post and term result objects, returns a small object identifying the ID and type; term results also include taxonomy. This is a result-format helper, not a lookup that fetches or validates the source object.
relevanssi_return_off()
Returns the literal string 'off'. Useful as a filter callback where a string setting is expected, rather than the Boolean false.
relevanssi_sanitize_hex_color($color)
Validates a hexadecimal colour using WordPress-compatible handling. Accepts an empty string or a # prefixed three- or six-digit value; an invalid value does not become a usable colour.
relevanssi_search_form($atts, $modal_context = false)
Returns the search-form HTML using the same attributes as the searchform shortcode. Pass an attribute array; $modal_context changes relevant modal-form markup. Echo the returned string when displaying it.
relevanssi_show_matches($post)
Returns the match-breakdown HTML using prepared hit counts on a Relevanssi result object. It is not an independent index inspection.
relevanssi_strip_invisibles($text)
Removes invisible elements and their contents, including scripts, styles, embedded objects, iframes, del, and SVG, plus HTML comments. Returns the remaining text.
relevanssi_stripos($haystack, $needle, $offset = 0)
Returns a case-insensitive substring position or false when no match is found, using multibyte functions where available. Position 0 is a valid match; compare the result with false strictly.
relevanssi_strlen($s)
Returns string length using mb_strlen() when available, otherwise strlen(). The fallback counts bytes for multibyte text.
relevanssi_strtolower($str)
Returns the lowercase string using multibyte handling when available, with a standard strtolower() fallback.
relevanssi_substr($str, $start, $length = null)
Returns a substring beginning at $start, with an optional maximum length. Uses multibyte handling when available; a null length takes the remainder of the string.
relevanssi_the_excerpt()
Prints the current Loop object's post_excerpt inside a paragraph after filtering it with wp_kses_post(). Checks password protection. It displays an existing excerpt rather than generating a new one.
relevanssi_the_permalink($post = 0)
Prints the permalink returned by relevanssi_get_permalink(), escaped for URL output. Uses the current post when the argument is omitted.
relevanssi_the_title($before = true, $after = '', $echoed = true)
Uses the current Loop post's highlighted title, or its original title. Prints by default; use an empty-string $before and $echoed = false to return it. The legacy call relevanssi_the_title(false) also returns the title. $before and $after add surrounding markup.
relevanssi_truncate_index()
Empties the Relevanssi index and returns a success Boolean. This is destructive index maintenance; content will need indexing again. It does not delete WordPress posts.
relevanssi_update_log($query, $hits, $source = '')
Attempts to record a search query, hit count, and optional source identifier in the search log, subject to the logging checks. Returns whether the entry was logged. Writes stored data when successful.
relevanssi_update_words_option()
Premium only. Rebuilds the stored relevanssi_words dictionary from indexed term frequencies for spelling correction. This writes an option and can be expensive on a large index; it is not an ordinary display helper.
relevanssi_user_agent_is_bot()
Returns whether the current HTTP_USER_AGENT matches Relevanssi's bot rules. It is a heuristic based on the reported user agent, not proof of a visitor's identity.
Maintenance and compatibility
relevanssi_index_doc(), relevanssi_remove_doc(), relevanssi_build_index(), and relevanssi_truncate_index() change the search index. In particular, the default relevanssi_build_index() call starts by emptying the existing index. Do not call a full rebuild or truncate function during an ordinary page request.
When reindexing an existing post, consider $remove_first = true to replace its old entries, and $bypass_global_post = true to ensure the supplied post is used instead of an unrelated global post. Supply the intended custom-field selection, for example the value from relevanssi_get_custom_fields(). Confirm the affected result afterwards.
Older references listed relevanssi_get_term_taxonomy(). It is not available in the version covered here. For a known taxonomy term, use WordPress’s get_term() and inspect the returned term’s taxonomy property, checking for errors and missing terms.
Object-conversion and text-processing helpers are not substitutes for validation or permission checks. Keep custom integration code scoped to its intended query and data. For query customisation, prefer the documented filter hooks where an appropriate hook exists.
27 Comments.
I have a long list of zip codes that I want to add to the plugin to return our locations page. Can I mass upload these or must I do this individually?
Ryan, I don’t understand the question. What do you mean “mass upload”? If you plan to do this with redirects, then yes, you need to add the redirects individually, but you can also just add the zip codes to the post content and have Relevanssi index.
Using the free version of Relevanssi, where does the theme get altered so that search terms are highlighted in the results?
Dave, as long as your theme is using
the_excerpt()to print out the excerpt, the highlighting should work automatically. If it’s not, you need to edit the search results template (usually search.php).Please guide how can i show the search result if the searched word is in the last of the post.. By default the results starts with the first paragraph. if the word is in the last paragraph it is not shown in the result.
Arlsan, Relevanssi should show the part of the post that has the searched term, whether that is in the first or the last paragraph. If you’re just seeing first paragraphs, make sure you have enabled Relevanssi-generated excerpts. If you have, and you’re still seeing the basic excerpts, make sure your theme is using
the_excerpt()to show the excerpts.I just set-up the plugin.
I get full posts when I search.
Can you explain how, if possible, I can only show the excerpts?
Richard, you need to edit your search results template. It’s likely using
the_content()to print out the post content. Replace that withthe_excerpt()to see excerpts.Hi there! I’m using Relevanssi to boost the search of a wordpress site I’m developing. I managed Relevanssi to get search results for titles, contents, categories and tags. Then I was trying to highlight the terms for each situation. For the tags I saw there is a function called relevanssi_the_tags(), but it’s returning me the whole link of the tags as strings.
So where there should be only the tag name, such as “Bangu”, the whole link is printed like “
<a href=”http://localhost/pos2017/tag/bangu/” rel=”tag”>Bangu</a>“.Any clues on how to solve this?
Cheers,
Willian.
relevanssi_the_tags() is the equivalent of the WordPress default the_tags(), which does the same thing. If you want just a highlighted list of tags, get the tags somewhere else, put them in a string and then use relevanssi_highlight_terms() on that string.
This should probably be fairly close to what you want: echo relevanssi_highlight_terms(get_the_tag_list(”, ‘, ‘), get_search_query());
Yes. It worked! Doing this solved the problem:
$tagList = strip_tags(get_the_tag_list(”,’, ‘,”));
And then I’ve put $tagList as an argument inside relevanssi_highlight_terms() .
Thank you so much for your help.
Cheers! o/
We have seemingly endless text pages like http://www.britting.de/wordpress/saemtliche-werke/bd-7-die-windhunde/. When Relevassi highlights a found tem there, it may be far down the page. Is there a way to have Relevassi scroll down to show the (first) highlighted appeareance smack in the visible window?
I guess it is possible to write some Javascript that finds the highlighted content and scrolls to it. Here are some methods for doing this: http://stackoverflow.com/questions/1586341/how-can-i-scroll-to-a-specific-location-on-the-page-using-jquery
Thank you for your encouragement, Mikko! The javascript addition has to be placed into the target page, right? Or is there a way to get it into the URL-link that gets me there? That would be fabulous for quotes to certain text passages, but this probably goes beyond Relevassi … Incidentally I still sometimes use “name” in my blooger blog and it keeps working.
In order for the link to work, there would need to be an anchor on the result page. I suppose that’s possible as well, but it’s really up to your theme and not Relevanssi.
Sorry, we are not able to do this, turns out, for “intellectual reasons” (too dumb). Might it not become standard to always move or scroll the result page to the highlight? I see no reason not to always do it. After all, the searcher wants to find exactly what she’s looking for, not the top of a page containing (for him just hopefully) the search clause? Thank you for considering.
It’s not a standard feature, because it’s hard to do (as you’ve noticed) and requires things that can’t really be standardized and need to be done on per site basis.
I also don’t think it’s always the correct thing to do – in most cases as a user I’d just get annoyed by this. I can use the browser on-page search, if I need to find a part of the page, but in general I’d prefer to read the page from the beginning.
We are in a special situation, perhaps. We have 23 full books, each a single (!) web page, with all the texts of a lifetime of a defunct author (http://www.britting.de/wordpress/saemtliche-werke/). Could you suggest me someone to help us in a paid effort? Private correspondence to Fritz@Joern.De is ok. I guess finding and spotting (scrolling to) must still be less of an effort, than to manually separate the pages into about thousand pieces. (I haven’t found search engines remembering “name” entry points to closer spot the target.) Here a special name marker (like the command to highlight something) would have to be plugged into the WordPress’ output page. (My dream would be browsers that can be told from the outside to search for a specific word in a page, so you could better reference something in a page … )
Hire a local web developer, that’s probably the easiest approach.
Thanky, Mikko – you are fast! We’ll try and let know.
When i add product using php code not from wordpress dashboard. Then relevanssi doesn’t take this product it it’s search util i open the product page from dashboard and click on update button. How can i solve this problem ?
Thanks,
Make sure your code triggers “wp_insert_post” hook after the post is added. Relevanssi relies on that, so if the hook is triggered, Relevanssi will index the post.
i can’t get the excerpt to display using get_excerpt or the relevanssi version of get_excerpt. all i get is […] and I’ve tried adding manual excerpts to a few posts tos ee if that would help, but no luck! Any ideas?
Does the_excerpt() work?
No, which baffles me. Right now I’m using a sloppy fix to at least get *something* to show up… but it obviously doesn’t have the nice excerpts with the highlighted search terms like I was hoping for:
I’d check to see if there’s something weird in your search results loop. Does the global $post get set properly? Try a var_dump($post) – do the post objects look good? If Relevanssi is creating excerpts as it should, there should be an excerpt in $post->post_excerpt.