Useful functions in Relevanssi

Relevanssi has some useful functions that can be helpful. Going through the source code looking for them is not fun, so here’s a list of functions that I think can be used outside Relevanssi code.

These all are available in both free and Premium unless noted otherwise. When using the functions, it’s always wise to wrap them in function_exists() block to avoid error messages when Relevanssi is for some reason deactivated:

if ( function_exists( 'name_of_the_function' ) ) {
    name_of_the_function( $parameter, $parameter );
}

Function documentation

Functions

relevanssi_add_apostrophes( string $string )
Returns the string wrapped in apostrophes.

relevanssi_add_quotes( string $string )
Returns the string wrapped in quotes.

relevanssi_add_synonyms( string $search_query )
Adds synonyms to $search_query.

relevanssi_build_index( bool|int $extend_offset, bool $verbose, int $post_limit, bool $is_ajax )
Indexes documents. If $extend_offset is numeric, offsets indexing by that match. If the value is false, Relevanssi truncates the index before indexing. $post_limit controls how many posts are indexed at once.

relevanssi_close_tags( string $html )
Returns the string with all open HTML tags closed. Not foolproof, but works reasonably well.

relevanssi_debug_echo( string $notice )
In WP_CLI context, prints out $notice with WP_CLI::log(), otherwise echoes it out.

relevanssi_do_excerpt( object $post_object, string $query, int $excerpt_length, string $excerpt_type )
Creates an excerpt for the post passed as the parameter, based on the search query in $query. If $excerpt_length and $excerpt_type are not set, the values are taken from Relevanssi settings.

relevanssi_do_shortcode( string $content )
Processes shortcodes in $content, based on Relevanssi shortcode processing settings and making sure the global $post is not changed by the shortcodes.

relevanssi_flatten_array( array $array )
Recursively flattens a multidimensional array to produce a string.

relevanssi_from_and_to( array $request, string $from )
Generates a date range based on the $request array. Can do direct dates, “this year”, “this month”, “last month”, “this week”, “last week”, “last 30 days”, “last 7 days”.

relevanssi_generate_missing_terms_list( WP_Post $post )
Generates the “Missing:” missing search terms element for the post from the missing terms stored in $post->relevanssi_hits[‘missing_terms’].

relevanssi_get_an_object( int|string|WP_Post $source )
Returns an array containing a post object and the $source format. The $source can be a post ID, **type**id string or a post object.

relevanssi_get_attachment_suffix( int|WP_Post $post )
Returns the file suffix from $post->guid.

relevanssi_get_current_language( bool $locale )
Returns the current locale or language code (based on $locale, which defaults to true) for the current post if global $post is set or the site in general. Compatible with WPML and Polylang.

relevanssi_get_post( int|string $post_id, int $blog_id )
A wrapper for get_post() that supports users and taxonomy terms and uses the Relevanssi post object cache.

relevanssi_get_post_object( int|string $post_id )
A wrapper for relevanssi_get_post() that also returns users and taxonomy terms.

relevanssi_get_post_status( int $post_id )
Returns the post status using the Relevanssi post object cache.

relevanssi_get_post_type( int $post_id )
Returns the post type using the Relevanssi post object cache.

relevanssi_get_term_tax_id( int $term_id, string $taxonomy )
Returns the term taxonomy ID from term ID and taxonomy.

relevanssi_get_term_taxonomy( int $term_id )
Given a term id, the function returns the taxonomy of the term.

relevanssi_get_the_title( int|WP_Post $post )
Returns the highlighted post title from $post->post_highlighted_title.

relevanssi_launch_ajax_action( string $action, array $payload )
Fires a wp_remote_post() call to admin-ajax.php with the specified action. Adds the nonce parameter.

relevanssi_mb_strcasecmp( string $str1, string $str2, string $encoding )
Multibyte-friendly case-insensitive string comparison using strnatcmp() or strnatcasecmp().

relevanssi_mb_trim( string $string )
Trims non-breakable spaces, null bytes and whitespace in a multibyte-friendly manner.

relevanssi_remove_doc( int $post_id, bool $keep_internal_links )
Removes the post from the Relevanssi index. If $keep_internal_links is true, does not remove internal link indexing for the post.

relevanssi_remove_quotes( string $string )
Returns the string with all quotes removed.

relevanssi_return_id_parent( WP_Post|WP_Term|WP_User $post_object )
Returns an object with attributes ID and post_parent set, supporting also terms and users (no post_parent for these).

relevanssi_return_id_type( WP_Post|WP_Term|WP_User $post_object )
Returns an ID, type object. For posts, type is “post”; for terms, it’s “term” and the taxonomy attribute is also set; for users, type is “user”.

relevanssi_return_off()
This function returns “off”.

relevanssi_sanitize_hex_color( string $color )
The same as sanitize_hex_color(), but this is always available.

relevanssi_search_form( array $attributes )
Prints out the Relevanssi search form like the “searchform” shortcode does. The attributes are the same as with the shortcode.

relevanssi_show_matches( object $post )
Returns the search results breakdown (how many hits in body, title, terms, custom fields and so on).

relevanssi_strip_all_tags( string $content )
Strips all tags from $content, but keeps non-tags that look like tags. Also removes all HTML comments.

relevanssi_strip_invisibles( string $text )
Removes style, script, object, embed, applet, noscript, noembed, iframe and del tags with their comments. Also removes HTML comments.

relevanssi_strip_tags( string $content )
Removes all HTML tags from $content, except the ones that are listed in the relevanssi_excerpt_allowable_tags option. Adds extra spaces after certain tags (p, be, headings, div, blockquote, hr, li, img) to make sure words are not stuck together after the tags are removed.

relevanssi_stripos( string $haystack, string $needle, int $offset )
Wrapper for stripos() that uses mb_stripos() if available, otherwise falls back to mb_strpos() and mb_strtoupper() and finally to strpos() and strtoupper().

relevanssi_strlen( string $string )
Wrapper for strlen() that uses mb_strlen() if available, otherwise falls back to strlen().

relevanssi_strtolower( string $string )
Wrapper for strtolower() that uses mb_strtolower() if available, otherwise falls back to strtolower().

relevanssi_substr( string $string, int $start, int|null $length )
Wrapper for substr() that uses mb_substr() if available, otherwise falls back to substr().

relevanssi_truncate_index()
Empties the Relevanssi index.

relevanssi_update_log( string $query, int $hits )
Logs the search query in $query to the Relevanssi search log with the number of hits found in $hits.

relevanssi_user_agent_is_bot()
Returns true if $_SERVER[‘HTTP_USER_AGENT’] is on the Relevanssi bot block list.

27 comments Useful functions in Relevanssi

  1. 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?

      1. 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:

        1. 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.

  2. 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,

      1. 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.

        1. 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.

          1. 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.

          2. 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.

          3. 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 … )

  3. 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.

    1. 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());

      1. 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/

    1. Richard, you need to edit your search results template. It’s likely using the_content() to print out the post content. Replace that with the_excerpt() to see excerpts.

  4. 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.

    1. 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.

  5. Using the free version of Relevanssi, where does the theme get altered so that search terms are highlighted in the results?

    1. 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).

  6. 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?

    1. 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.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *