Relevanssi has lots of filter hooks you can use to modify how the plugin behaves. Most of these are pretty advanced and an average user probably doesn’t have to worry about them, but if you’re going to do something more demanding, knowledge of these filters will help.
If you do something that would be made easier by a new filter, please let me know – I do like adding new filter hooks, as that is a very easy way to add flexibility to the plugin with little effort.
For more information on how to use filters, see WordPress Actions and Filter Hooks: A Guide for Non-Developers.
(Small Relevanssi tip: I did not want this post to be found in search with the names of the filter hooks in the list below. To stop that, I formed a group of all the blocks that form the list and gave the group a CSS class relevanssi_noindex
. That excludes the whole list from the Relevanssi index nice and easy!)
Filter hooks
Indexing
- relevanssi_comment_author_to_index
- relevanssi_comment_content_to_index
- ⭐️ relevanssi_content_to_index
- relevanssi_custom_field_value
- relevanssi_default_punctuation_replacement
- relevanssi_disabled_shortcodes
- relevanssi_disable_stopwords
- ⭐️ relevanssi_do_not_index
- relevanssi_forbidden_post_types
- relevanssi_forbidden_taxonomies
- relevanssi_get_approved_comments_args
- relevanssi_index_attachment_revision_types
- relevanssi_index_comments_exclude
- relevanssi_index_content
- relevanssi_index_custom_fields
- relevanssi_index_get_post_type
- relevanssi_index_titles
- relevanssi_indexing_adjust
- relevanssi_indexing_data
- relevanssi_indexing_limit
- relevanssi_indexing_query
- ⭐️ relevanssi_indexing_restriction
- relevanssi_indexing_tokens
- relevanssi_indexing_values
- relevanssi_post_author
- ⭐️ relevanssi_post_content
- relevanssi_post_content_after_shortcodes
- relevanssi_post_content_before_tokenize
- relevanssi_post_title_before_tokenize
- relevanssi_post_to_index
- relevanssi_pre_indexing_query
- relevanssi_premium_tokenizer
- relevanssi_punctuation_filter
- relevanssi_remove_punctuation
- relevanssi_remove_stopwords_in_titles
- relevanssi_stemmer
- relevanssi_tag_before_tokenize
- relevanssi_valid_status
- Gutenberg: relevanssi_block_to_render
- Gutenberg: relevanssi_render_blocks
- Gutenberg: relevanssi_rendered_block
- Post type archives: relevanssi_post_type_additional_content
- Post type archives: relevanssi_post_type_archive_ok
- Post type archives: relevanssi_post_type_to_post
- Taxonomy terms: relevanssi_do_not_index_term
- Taxonomy terms: relevanssi_hide_empty_terms
- Taxonomy terms: relevanssi_tax_term_additional_content
- Taxonomy terms: relevanssi_taxonomy_term_to_post
- Taxonomy terms: relevanssi_term_add_data
- Users: relevanssi_user_add_data
- Users: relevanssi_user_data_to_index
- Users: relevanssi_user_index_ok
- Users: relevanssi_user_indexing_args
- Users: relevanssi_user_profile_to_post
Searching
- relevanssi_add_all_results
- relevanssi_author_query_filter
- relevanssi_block_one_letter_searches
- relevanssi_by_date_query_filter
- relevanssi_cached_post_object
- relevanssi_comparison_order
- relevanssi_date_query_filter
- relevanssi_date_query_non_posts
- relevanssi_default_tax_query_relation
- relevanssi_df_query_filter
- relevanssi_disable_stemmer / relevanssi_enable_stemmer
- relevanssi_exact_match_bonus
- relevanssi_fallback
- relevanssi_fuzzy_query
- ⭐️ relevanssi_hits_filter
- relevanssi_join
- relevanssi_log_query
- ⭐️ relevanssi_match
- relevanssi_missing_sort_key
- ⭐️ relevanssi_modify_wp_query
- relevanssi_ok_to_log
- relevanssi_order
- relevanssi_orderby
- relevanssi_parent_query_filter
- ⭐️ relevanssi_post_ok
- relevanssi_post_query_filter
- relevanssi_post_status_query_filter
- relevanssi_post_type_query_filter
- relevanssi_prevent_default_request
- relevanssi_query_filter
- relevanssi_results
- relevanssi_search_again
- relevanssi_search_filters
- relevanssi_search_form
- relevanssi_searchform_dropdown_args
- relevanssi_search_ok
- relevanssi_search_params
- relevanssi_show_password_protected
- relevanssi_sort_compare
- relevanssi_term_where
- relevanssi_valid_admin_status
- relevanssi_where
- relevanssi_wildcard_search
- Did you mean: relevanssi_didyoumean_alphabet
- Did you mean: relevanssi_didyoumean_query
- Did you mean: relevanssi_didyoumean_suggestion
- Did you mean: relevanssi_didyoumean_token
- Did you mean: relevanssi_didyoumean_url
- Did you mean: relevanssi_get_words_having
- Phrases: relevanssi_phrase
- Phrases: relevanssi_phrase_custom_fields
- Phrases: relevanssi_phrase_queries
- Phrases: relevanssi_phrase_synonyms
- Phrases: relevanssi_phrase_taxonomies
- Multisite: relevanssi_multi_results
- Multisite: relevanssi_multisite_public_status
- Multisite: relevanssi_site_results
- Spam blocking: relevanssi_bots_to_block
- Spam blocking: relevanssi_search_url_prefix
Excerpts and highlighting
- relevanssi_accents_replacement_arrays
- relevanssi_add_highlight_and_tracking
- relevanssi_allow_one_letter_highlights
- relevanssi_clean_excerpt
- relevanssi_custom_field_value
- relevanssi_disable_shortcodes_excerpt
- relevanssi_ellipsis
- relevanssi_entities_inside_code
- relevanssi_entities_inside_pre
- relevanssi_excerpt
- relevanssi_excerpt_post
- ⭐️ relevanssi_excerpt_content
- relevanssi_excerpt_custom_fields
- relevanssi_excerpt_custom_field_content
- relevanssi_excerpt_specific_custom_field_content
- relevanssi_excerpt_gap
- relevanssi_excerpt_part
- relevanssi_excerpt_query
- relevanssi_excerpts
- relevanssi_highlight_query
- relevanssi_highlight_regex
- relevanssi_highlight_tokenize
- relevanssi_optimize_excerpts
- relevanssi_permalink
- relevanssi_pre_the_content
- relevanssi_post_the_content
- relevanssi_post_to_excerpt
- relevanssi_pre_excerpt_content
- relevanssi_show_matches
- Missing terms: relevanssi_missing_terms_must_have
- Missing terms: relevanssi_missing_terms_tag
- Missing terms: relevanssi_missing_terms_template
Logs
- relevanssi_bots_to_not_log
- relevanssi_log_get_user
- relevanssi_log_query
- relevanssi_remote_addr
- relevanssi_valid_sources
Attachment reading
- relevanssi_accept_mime_type
- relevanssi_add_attachment_scripts
- relevanssi_attachment_server_url
- relevanssi_do_not_read
- relevanssi_get_attachment_posts_query
- relevanssi_get_attachment_posts_query_final
- relevanssi_get_attached_file
- relevanssi_get_attachment_url
- relevanssi_file_content
- relevanssi_pdf_for_parent_insert_data
- relevanssi_pdf_for_parent_query
- relevanssi_pdf_read_timeout
- relevanssi_send_pdf_files
Admin backend
- relevanssi_1day, relevanssi_7days, relevanssi_30days
- relevanssi_acceptable_hooks
- relevanssi_admin_search_blocked_post_types
- relevanssi_admin_search_capability
- relevanssi_admin_search_element
- relevanssi_admin_search_ok
- relevanssi_display_common_words
- relevanssi_init
- relevanssi_options_capability
- relevanssi_sidebar_capability
- relevanssi_tabs
- relevanssi_update_options
- relevanssi_update_translations
- relevanssi_user_searches_capability
- relevanssi_user_searches_limit
- relevanssi_user_searches_query_url
Related posts
- pre_relevanssi_related | post_relevanssi_related
- relevanssi_disable_related_cache
- relevanssi_related_args
- relevanssi_related_excerpt_length
- relevanssi_related_image_size
- relevanssi_related_output
- relevanssi_related_posts_cache_id
- relevanssi_disable_related_cache
- relevanssi_related_args
- relevanssi_related_excerpt_length
- relevanssi_related_image_size
- relevanssi_related_output
- relevanssi_related_posts_cache_id
- relevanssi_related_priority
- relevanssi_related_wide_limit
- relevanssi_related_words
Plugin compatibility
- relevanssi_page_builder_shortcodes
- ACF: relevanssi_acf_field_object
- ACF: relevanssi_acf_field_value
- ACF: relevanssi_blocked_field_types
- ACF: relevanssi_custom_fields_before_repeaters
- Oxygen: relevanssi_oxygen_element
- Oxygen: relevanssi_oxygen_section_content
- Oxygen: relevanssi_oxygen_section_filters
- WooCommerce: relevanssi_sku_boost
- WooCommerce: relevanssi_woocommerce_indexing
Removed filter hooks
relevanssi_default_meta_query_relation (‘OR’) Removed in 2.3.0 / 4.2.0
relevanssi_get_words_query ($query) (Removed in Premium 1.15.2)
relevanssi_index_taxonomies_args ($args) (Premium only) Removed in 2.0.2
This filter has been removed. The taxonomy term indexing doesn’t use get_terms()
anymore. The behaviour is still similar, and you can use relevanssi_hide_empty_terms
to enable the empty terms.
relevanssi_related_output_objects
This filter hook will be removed in the next version of Relevanssi. This filter hook is not needed for anything, as it filters a function return value you can just as easily modify without a filter hook.
Hello,
Thank you for such a great plugin and your awesome support !
I am using the networked version using a child theme from Twenty Eleven and WordPress 3.4.2 with Relevanssi Premium. Everything is working perfectly and I have implemented highlighting with css styling, “Did You Mean”, automatic indexing and stemming.
The question I have is: how to I save the state of a not found search term?
For example: I search for the term “spacewalk” and it is not found, so
I do not want to retype, I just want to edit the term “spacewalk” to “space walk”
I assume it is some sort of modification to the search.php file.
Any help would be greatly appreciated.
Mark
You can get the search term with get_search_query().
hi, what if i’d like to make a multiple pulldown filter so i can choose objects first by tipology, then after that by designer and so on? is there any way to achieve that? 🙂
Just add several dropdowns, Relevanssi can handle multiple filters.
I am having some difficulty finding examples to back up this documentation. Are there any examples of filters being use that I just am not seeing?
I have the premium version, and would like to be able to give users search options, so they can adjust the weight at search time. For example, one user may want to search everything. Another may want to limit their search to the “Artists” taxonomy (or make the weight of that taxonomy higher while lowering the weight of post titles an descriptions. Then a third user may want to search just track titles.
Maybe adjusting the weight is not the right approach, and there is some other aspect of the filters that should be using?
I have my Relevanssi indexing everything, so how do I apply the filters base on user-selected options in the search form? Any example code I can see? Any sites that actually do this kind of thing? I just can’t find anything,
If you want to use taxonomy filters, the best way is to create a tax_query (http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) and add it with relevanssi_modify_wp_query. Here’s a fairly thorough example. Doing a taxonomy dropdown is fairly easy (wp_dropdown_categories() helps a lot).
If you want to adjust weights, then you must use the relevanssi_weight filter; the approach is similar, read the user-provided values from query variables and use them in the filter. I think that’s too much control to give for users: it’s lots of work for you to write, and 99.99% of users will never use it.
Searchers in general just want to type words, anything more advanced is unlikely to see use.
How people will want to search will depend on the context. In my case I am indexing a second-hand record store. Depending on what they are searching for, they may want to lean towards a specific artist (in the artist taxonomy) or more towards a genre of music. They won’t be searching through big articles of text, but being able to find an artist that has been spelt ten different ways, will be very useful.
So if I understand correctly, I nee to write my own query form and back-end, using the standard WordPress techniques, and Relevanssi will kick in and direct the query towards its own indexes? Or have I misunderstood?
Yes, you’ve got it. Relevanssi understands almost everything mentioned in the WP_Query documentation: tax_query, meta_query, post_type and so on.
Thanks, I’ll have a play.
I’ve not had any luck at all. I have tried adding a tax_query, as shown in your example link, and nothing is getting filtered. The example is quite a few years old now – is it still correct?
I have this in my custom_search_filter:
$query->set(‘tax_query’, array(
‘taxonomy’ => ‘artist’,
‘terms’ => array(‘foobar’),
‘field’ => ‘slug’,
‘operator’ => ‘IN’,
‘relation’ => ‘AND’,
));
There is no “foobar” slug in the artist taxonomy, so I would expect everything to be filtered out, but no filtering is happening at all.
If I can get this working, I don’t see any mention in documentation of WP_Tax_query supporting wildcards on taxonomy term names or slugs. Is that supported, since it is central to my original problem?
Looks like you’re one array too shallow: wrap your array() in one more array() and it should work.
No wildcards in tax_query, it’s an exact match system.
Adding an array wrapper makes no difference. The query appears in the $query->query_vars array like this:
[“tax_query”]=>
array(1) {
[0]=>
array(5) {
[“taxonomy”]=>
string(6) “artist”
[“terms”]=>
array(1) {
[0]=>
string(6) “foobar”
}
[“field”]=>
string(4) “slug”
[“operator”]=>
string(2) “IN”
[“relation”]=>
string(3) “AND”
}
}
The fact that taxonomy terms cannot be searched using wildcards kind of defeats the main object of what I am trying to do. The user enters terms to search, and one option is for them to retrieve products that have taxonomy terms that match the keywords they have entered. I guess I am going to have to do a separate query to fetch a list of term IDs and then inject the IDs into the taxonomy filter (if I can get it to work).
Well, you can always use Relevanssi to search the taxonomy terms, then you can have wild cards. Tax_query is meant for dropdowns and exact match filtering anyway.
I thought I *was* using relevanssi using this filter? I’m confused.
Back to the beginning: I would like the user to be able to enter keywords into a search box, and those keywords to be used to match against taxonomy terms in a custom taxonomy, and return all posts (type products) for those matching taxonomies.
Can relevanssi, having indexed the taxonomies, support this, or not?
No – if you use tax_query, you’re not using Relevanssi. It is a direct MySQL query used to filter the results.
What you need is automatically done, all you have to do is to check couple of boxes on Relevanssi settings to make Relevanssi index and search the taxonomies you want to search. Then all your searches will be checked against those taxonomies. No need to mess with tax_query.
Sorry, I thought relevanssi took what was given to the query, with any additions added to the query in the relevanssi_modify_wp_query filter then formed its own query based on what it was given. I must have misunderstood.
If I set the global settings to only search in a single taxonomy, then what do I do for the next user that wants to search in a different taxonomy, and the user after that who wants to search in titles and post bodies? How do I change those search options per search, depending on what search options the user has ticked?
That’s a global setting, which you can’t modify per-user basis. Is it a huge problem if all searches match all taxonomies, post titles and bodies?
Yes, it is a problem, because it is not what the client wants. They can use Google for a one-search-fits-all. We are indexing locally using Relevanssi because we need more control.
Well, in that case what you want is not possible with Relevanssi.
I’ve worked around this problem now. When the search form is submitted with a second button called “artist_search”, that disables Relevanssi (two filters removed), empties the search term so it searches everything, fetches IDs of all the artist taxonomies that match the entered search term, adds those IDs into the query as a taxonomy join, then that fetches all products related to any taxonomy term that contains the artist name. Using the normal search button, and none of that happens so Relevanssi searches everything.
Hi, I am having issues getting relevanssi to use the AND relation when searching by both a custom tax and a category. what is the proper way to implement relevanssi_default_tax_query_relation?
I have tried : add_filter(‘relevanssi_default_tax_query_relation’, ‘AND’);
but nothing changes. I also tried to add it in a function simply as relevanssi_default_tax_query_relation (‘AND’); and that gives the white screen of death.
Any help is much appreciated
You need to add a function to that filter, and that function needs to return “AND”. Like this:
add_filter(‘relevanssi_default_tax_query_relation’, ‘isayand’);
function isayand($relation) {
return “AND”;
}
Ah thanks, I shoulda realized that but was having brain lock.
I am trying to use your “relevanssi_pre_excerpt_content” or “relevanssi_excerpt_content” hook to modify the search results, but I cannot seem to access the post information inside my function… here is what I have currently…:
add_filter(‘relevanssi_pre_excerpt_content’, ‘specificResults’);
function specificResults($content, $post, $query) {
return $post->ID;
}
Any help on how to get the post content for the search result would be helpful.
Thanks,
What are you trying to achieve here? At least the filter function should return the $content variable, after the modifications you’ve done to it. If you return the post ID, you’ll ruin the whole excerpts.
Yes I understand it would ruin the excerpts, that was just me testing trying to get to the post content. What I am hoping to do, is that I have some LONG tabular data with product information on a few pages of the site I am working on for my client. If able to access the Post content I was planning on detecting the post ID, if it matched those with the product tables, then iterate through the content and present each table row in the results with a link taking the client to an anchor tag for the row they had searched for.
The function reference above lists the $post as being passed through to the filter… but I cannot seem to access it.
Thanks
Ah, I know what your problem is. Your add_filter() call is missing the last two parameters, and because of that, only the first parameter is actually being passed to the function.
add_filter(‘relevanssi_pre_excerpt_content’, ‘specificResults’, 10, 3);
should work much better.
Do note that whatever data you put in the content in relevanssi_pre_excerpt_content will get mangled by Relevanssi excerpt-building algorithm.
Thank you Mikko, I am now able to access the Post data!
One more question if you will indulge me, is there a way to disable the excerpt size limit from within the filter? or is there another filter hook that would give me access to that?
To modify excerpt length on the fly, use the “pre_option_relevanssi_excerpt_length” filter.
I’m trying to use relevanssi_default_meta_query_relation to change the meta query relation to “OR” from the default of “AND” that I have set in the admin panel, but Relevanssi returns zero results. Here’s my code snippit:
add_filter(‘relevanssi_default_meta_query_relation’, ‘isayor’);
function isayor($relation) {
return “OR”;
}
I modified code that you posted in answer to another persons question. I want to leave the default set to AND, but under certain circumstances, switch to using OR.
Thanks for your help!
‘relevanssi_default_meta_query_relation’ sets the meta_query relation setting, not the general search operator that you set on the settings page. These are two completely different settings.
Relevanssi Premium supports setting the operator on a per-query basis like this: http://www.example.com/?s=search+term&operator=OR – but that doesn’t work in the free version.
Thanks Mikko, looks like it’s time to upgrade to Premium!
Does the relevanssi_default_tax_query_relation works in the free version?
I see no change in if i use this code or not in the sql query string
add_filter(‘relevanssi_default_tax_query_relation’, ‘relationAnd’);
function relationAnd($relation) {
return ‘AND’;
}
i need a search for the query and two taxenomys where the post has to be in both custom taxenomies
It does work in free version. Does your tax_query perhaps override it?
right now it doesn’t i will look deeper into it and reply if i still get stuck.
One feature request — the ability to filter output of relevanssi_didyoumean. Defaults to “$pre<a href=”$url”>$suggestion</a>$post”, but it would be really helpful to be able to filter the result to show as not just a link, or to add classes to the link. I’ve had to do both, and usually achieve these results through creative (and unsemantic!) JS/CSS hacks.
Sure. Next version will have
echo apply_filters(‘relevanssi_didyoumean_echo’, “$pre$suggestion$post”);
so you can change it like this now and still have it work after updates.
Hey Guys, just doing an evaluation here. I can’t find clear documentation anywhere on this matter so hopefully someone can clarify. In my use case, I have a complex taxonomy with a tree of about 6 categories, each with 5-50 subcategories. We want to offer the user the ability to have an amazon or linkedin like filtering experience. So the two features we are looking for are:
a. Start with a search query and then apply filters using checkbox. User should be able to apply multiple filters from the taxonomy. These should be AND filters. How would you go about doing this?
b. User should be able to simply browse the categories and apply filters WITHOUT a search term. In this case, user is simply drilling down and selecting check boxes from the taxonomy to apply a filter. No search term would be required. These would also be AND filters. How would you do this?
Are these two things possible? How much custom coding would this require. We’ll hire someone to do it but if it’s highly complex, it might be better to use ElasticSearch.
Thanks in advance!
These both are feasible, though B doesn’t exactly need Relevanssi. You need to write code that reads in the checkboxes and creates a proper tax_query object from the taxonomy parameters and passes that to Relevanssi. For B, you also need to write some code that’ll actually fetch the posts from the database (see https://www.relevanssi.com/knowledge-base/using-relevanssi-without-a-search-term/).
I’m trying to use the relevanssi_didyoumean_url filter, and there is one bit that I’m having trouble with. I need the url to be http://mysite.com/video/?_sf_s=searchterm. I added the following to my theme’s functions.php file:
add_filter('relevanssi_didyoumean_url', 'rlv_modify_url');
function rlv_modify_url($url) {
$url = get_bloginfo('url') . '/video/';
$url = esc_attr(add_query_arg(array(
'_sf_s' => urlencode($closest)
), $url ));
return $url;
}
Everything except the urlencode($closest) bit is working. What can I use instead to pull the search term into the filter properly?
$closest is not defined in your function. You can probably get what you done by replacing “?s” in the $url with “?_sf_s”.
Thanks.. I figured out a different solution.
Hello, I want to change the AND relation to OR in the following sql, i want to filter if the string in the post content or in the metaquery. How can i change it ?
string ‘SELECT relevanssi.*, relevanssi.title * 5 + relevanssi.content + relevanssi.comment * 0.75 + relevanssi.tag * 0.75 + relevanssi.link * 0 + relevanssi.author + relevanssi.category * 0.75 + relevanssi.excerpt + relevanssi.taxonomy + relevanssi.customfield + relevanssi.mysqlcolumn AS tf
FROM wp_relevanssi AS relevanssi INNER JOIN wp_postmeta ON ( relevanssi.doc = wp_postmeta.post_id ) WHERE (term LIKE ‘%test’ OR term LIKE ‘test%’) AND (
( wp_postmeta.meta_key = ‘_itg_pre_requisites’ AND wp_postmet’… (length=653)
You can use the “relevanssi_query_filter” to modify the query before it is run.
if i use $query =str_replace(“AND (“, “OR (“,$query); in relevanssi_query_filter this will not affect the filtering in the future?
It affects all queries as long as the filter is in place. If you need finer control, figure out a way.
Is there a way to change the relation in where condition ?
That filter gives you access to the complete query string, you can make any changes you want to.
How can i retrieve the relevanssi settings from database?
See Relevanssi source code for the setting you need. The settings are all named relevanssi_something.
Hello,
I edit the relevanssi search query using relevanssi_query_filter filter as follow :
SELECT relevanssi.*, relevanssi.title * 5 + relevanssi.content + relevanssi.comment * 0.75 + relevanssi.tag * 0.75 + relevanssi.link * 0 + relevanssi.author + relevanssi.category * 0.75 + relevanssi.excerpt + relevanssi.taxonomy + relevanssi.customfield + relevanssi.mysqlcolumn AS tf
FROM wp_relevanssi AS relevanssi
LEFT JOIN wp_postmeta
ON ( relevanssi.doc = wp_postmeta.post_id )
WHERE relevanssi.term = ‘sql’
OR ((wp_postmeta.meta_key = ‘pre_requisites’
AND wp_postmeta.meta_value LIKE ‘%sql%’ )
OR (wp_postmeta.meta_key = ‘audience’
AND wp_postmeta.meta_value LIKE ‘%sql%’ )
OR (wp_postmeta.meta_key = ‘course_id’
AND wp_postmeta.meta_value LIKE ‘%sql%’ ))
ORDER BY tf DESC
This query take 5.2057 seconds
note that the wp_relevanssi contain 3718 rows.
Why the query take long time execution ?
Likely those postmeta queries. You could try removing the meta_query and instead using relevanssi_hits_filter to filter out the unmatching results.
I try to use the default query without any changes the ajax request take 5 second, do you have any suggestion ?
Yes: forget Relevanssi and switch to something that runs outside your server, like Swiftype or Solr.
Hello,
How i can know the location of hits, in other word how can i know if the hit in the title of the post or description ?
Thanks,
There’s no easy way to know, but you can use the “relevanssi_match” filter hook to dig into it.
Yes i think it’s the only way.
thank you alot.
There is a filter to add a simple English stemmer, and Relevanssi has WPML support. Is it possible to add a second stemmer and let the stemmers operate on posts in their language only? Currently, my Dutch terms are being stemmed as well, with incorrect results.
NB: The simple English stemmer turns “wordpress” into “wordpr”.
Nope, not really possible. In multilingual cases it’s best not to stem at all. Relevanssi could stem English posts with an English stemmer and Dutch posts with a Dutch stemmer, but Relevanssi can’t tell which language the user is using and doesn’t know which stemmer to use for search queries.
Yes, “WordPress” becomes “wordpr”. That’s correct, if not very logical. That’s why it’s called a simple stemmer. A proper Snowball stemmer wouldn’t do anything to that, I think.
Is it possible to search with AND and then OR so If I look for Red Blue trainers , it shows red, Blue trainers and then shows all red trainers, blue trainers and then anything with red, blue or trainers.
Thanks
Yes. It’s best done with a relevanssi_hits_filter. Search with OR, then add extra weight for posts that match all words. Here’s an example, though I’d increase the multiplier from 2 to maybe 20.
Firstly you’re response times are amazing!
Secondly, Brilliant thank you.
So I add the filter from that link to functions.php
In the relevassi settings do I need to set the default operator for the search to AND or OR with this please.
The operator needs to be OR in order to get all the results in, the filter will then sort them with the AND results first.
Hi team,
I am using your plugin on one of my website https://www.pentegra.com/?s=fiduciary.
I would like to set the ‘SET OPTION SQL_BIG_SELECTS=1’ while user performs the search on my site.
I try to use action hook as mentation on https://www.relevanssi.com/user-manual/filter-hooks/
You can check my code below.
function relevanssi_pre_indexing_query_action_hook( ) {
global $wpdb;
$wpdb->query(‘SET SQL_BIG_SELECTS=1’);
}
add_action( ‘relevanssi_pre_indexing_query’, ‘relevanssi_pre_indexing_query_action_hook’ );
But this code doesn’t have any effect.
Can you guide me how to write the action hook or where I am making mistake?
Looking forward to the positive response.
Kind regards,
Hem
As the name suggets,
relevanssi_pre_indexing_query
runs before indexing. It doesn’t run when searching. You can usepre_get_posts
to do actions before Relevanssi is run in searches.Can you provide an example of how one would use relevanssi_fallback in functions.php? I can’t seem to figure it out. Here’s the best I can come up with:
add_filter( ‘relevanssi_fallback’, ‘fallback_search’ );
function fallback_search( $args ) {
$args[‘args’][‘q’] = “pictures”;
return $args;
}
Jonathan, let’s ask it this way: what do you want to achieve? Your function needs to run the search, so just adjusting the parameters is not enough. If you want to search for “pictures” if the default search doesn’t find anything, the function would look like this:
Ahh, that does it. I wasn’t sure how to actually run the search. Though I guess what I really want to do is hook into the script after it writes out its output, so I can show some custom content.
For example, I can use the “the_content” filter to add stuff to the page before or after a post. How can I hook into Relevanssi and output custom content after the search results (especially if there are no results)?
Jonathan, you don’t hook into Relevanssi for that. The output is something your theme does, so you need to modify your theme search results template. Just add the content to the search results template.
I need some help!
What i want is to intercept the results of a search, and using only the postID’s of the result-posts to create my own layout that would suit the layout of my other pages in my website (microverhalen.nl).
I tried this with no results 🙂
add_filter(‘relevanssi_results’,’myresults’,10,3);
function zoekresultaat($results) {
foreach ($results as $post) {
return $post->ID;
}
}
Can any help me with a solution?
Are you sure you want just the post IDs? In most cases, when replacing the search results template, you start from a post loop which uses the whole post objects. If the first thing you’d do with the post ID is to fetch the post object, just use the post objects. Saves time and effort.
But if you really want just the post IDs and know what you’re doing, you can make Relevanssi return post IDs with this bit of code:
Now Relevanssi will return you an array of post IDs instead of post objects. But I’m pretty sure you really want the post objects.
Thank you very much, Mikko… For me the array of postid’s will do, I think 🙂
I like to display the results just with some special information about the individual posts: picture, title, author and link.
Will let you know if I will manage that!
Thanks for your swift response!!!
Kind regards,
Hans Stavleu
Put this into my functions.php:
add_filter( ‘relevanssi_modify_wp_query’, ‘rlv_just_ids’ );
function rlv_just_ids( $query ) {
$query->set( ‘fields’, ‘ids’ );
foreach ($ids as $id) {
$post_title = get_the_title($post_id);
echo $post_title;
}
return $query;
}
still getting the same output as before.
I guess i am thinking the wrong way.
Hans
Yes, you are. I would recommend hiring a WordPress developer to build this for you. If that’s not possible, then the first step is to study how the WordPress template hierarchy and post loops work.
The function I gave you is complete; that’s all it takes to have Relevanssi give you post IDs. Don’t modify that.
The results are not printed out in the Relevanssi filters. That’s the job for the search results template. You will need to have a post loop in the search results template, and there you can modify the way the results show up.
Looking at what you’re trying to do here, you really should be using the post objects, like I said – then you can just echo $post->post_title, instead of having to call get_the_title(). You’re only making life harder for yourself by using the post IDs, it’s not helping you.
But you’re pretty far off right now. Go read this: https://codex.wordpress.org/The_Loop It should help you understand how the post loop works.
Thank you very much, I understand what you said!
I am not really in the circumstances to hire someone for my hobby project. But I now know where i have to find the solution 🙂
Kind regards,
Hans
Thanks again,
All I want is the ID’s (via a shortcode) in a ‘normal’ page (Add Page in Dashboard) and not in Search.php.
As you can see in https://microverhalen.nl, I made all kind of overviews of posts, and now i want to do that also for Search Results.
Kind regards,
Hans
Ah, in that case you should look into using
relevanssi_do_query()
to get the results. See the instructions here. You could for example create a shortcode that runs the search and displays the results, so you can then add the shortcode wherever you want.Thank you very much for all your effort to help!
That function does exactly what i was looking for 🙂
Implementation went smoothly! Got it working within a few minutes.
Thanks, Mikko!
Not sure if this is the correct thread to post on, but here is my question. I am running a multisite, with subsites like a social network. In the social network, “posts” are created by each user on the network and it is not the traditional posts of wordpress which makes a search a bit different. I am hoping to create a search that includes content from user profile fields (name, location, etc…) as well as searchable content from each user’s posts. Can this be configured in relevanssi in some way?
Shea, Relevanssi Premium can fetch user profiles. The posts can be searched for if they appear as posts in the wp_posts database, but otherwise, it’s not possible.
We are using Relevanssi for searching a mix of English and Chinese characters and there are some challenges specific to Chinese we are trying to solve. We would like to index every single substring of a term (so “term” would index as t, te, ter, term, erm, rm, m, er, e, r). Very crazy for English, but very useful for Chinese. We have already set the min word length to 1 (and added every single English char to the stop list to avoid craziness there).
Relevanssi by default does not do the single characters at the ends of words and also does not index the middles. I see the fuzzy query gets you the inside (still trying to figure out how to implement it) but does it get you the single characters as well? Is there a better way to go about this?
Thanks!
Chris, Relevanssi just doesn’t work very well with Chinese. My recommendation would be to get a search engine that actually works in Chinese. I’m not aware of any, but I guess there must be some.
You can do the substring indexing, and you can do it only for Chinese text. I don’t think you should do it with English text, because that will lead to a huge amount of garbage results. You should probably come up with a filtering function that goes through your post content (using the
relevanssi_post_content
filter hook and other necessary similar fields), finds all the Chinese words and then splits them up in substrings and adds those to the post content.Once you do that and also enable one-letter searching (do note that setting the minimum word length to 1 is not enough, you also need to unblock the one-letter searches with this:
add_filter( 'relevanssi_block_one_letter_searches', '__return_false' );
, otherwise one-letter searches will not work), I don’t think you need to adjust the fuzzy matching. Just set Relevanssi to always do partial matching, and you should be reasonably fine.Hi Mikko
First of all I would like to thank you for your plugin. It’s really helpful.
I just have a concern regarding the searching logic, I see that the logic considers the weight based on the tf value calculated which reflects the number of times the word is mentioned in a post. This approach could cause some confusion when a sentence containing a keyword present in most of the articles as the weight will give priority to the posts containing this specific keyword more than other posts containing the whole sentence but the keywords are not repeated. For my case, I preferred to adjust the weight through the words mentioned rarely by dividing the weight by the $matches->count and the tf value to focus on the posts containing more words of the searched sentence.
I did workaround on that through this function:
function adjust_match_weights($match, $idf, $term ) {
global $wpdb;
$term_count = $wpdb->get_var(“SELECT COUNT(term) from wp_ecrs_relevanssi WHERE term = ‘$term'”);
$match->weight = $match->weight / ($term_count * $match->tf);
return $match;
}
add_filter(‘relevanssi_match’,’adjust_match_weights’, 10, 3);
It’s working fine. However I needed to add a separate query for each term through the loop to get the $matches->count value as the hook relevanssi_match doesn’t included. I don’t think this is the best practice due to increasing the database queries when $matches->count was already accessed before. It can even be used if I updated the core but not through accessing the relevanssi_match filter. Could the $matches object be included in the apply_filters function in a next update?
Also regarding the synonyms, I noticed that if I added a synonym key and value it’s stored in the options table. However, if I came afterwards and wrote another synonym key and value it will overwrite the previous value in the database. I think that a simple concatenation function can solve this issue in the interface.php file.
Is there a concern changing this line:
$value = str_replace( $linefeeds, ‘;’, $_REQUEST[‘relevanssi_synonyms’] );
To be that way?
$value = get_options(‘relevanssi_synonyms’). “;”. str_replace( $linefeeds, ‘;’, $_REQUEST[‘relevanssi_synonyms’] );
I tried it and it worked, however there are no filters here which means that I need to update it in the core. If I did so, I will need to change it every time I update the plugin. Couldn’t this be incorporated in a next update?
Thanks
Mohamed, I’m not really catching the reasoning behind your weighting suggestion. The TF × IDF weighting has been an industry standard for 60 years and for a good reason; it generally works really well. If you want to make a post with a smaller weight for a particular keyword rank higher for that keyword, the easiest solution would be just to pin it using the pinning feature in Relevanssi Premium: that will guarantee first ranking in the search, without any additional code.
Your filter function is indeed not good for the performance: running all those extra queries will hurt the performance a lot. Why not use IDF instead? It’s already passed as the parameter to the filter, and while it’s not exactly the same as the term count you’re calculating, I think it’s generally the more useful number. Looking at the IDF is more helpful than the raw TF across the whole database, because the raw TF has no upper bound, while IDF has (the number of documents).
Passing the $matches array as a parameter to the filter doesn’t help, because there’s no $matches->count value in it – Relevanssi doesn’t calculate the raw TF.
Your suggested fix for the synonym interface would break it badly. Your change would make it impossible to ever remove synonyms, and the same synonyms would be duplicated many times every time the synonyms are saved. There’s no need to fetch the option value, because $_REQUEST[‘relevanssi_synonyms’] already includes all the synonyms, both old and new. If it doesn’t on your site, then there’s something wrong with the way your site works. It’s working as it is.
Well, I am not really aware of the exact search logic used but I have been testing it on many queries I had in my database and I had a problem with the indexing. When I added the filter the indexing worked as it should be.
Maybe my case needs a special requirement as people usually search by a statement not by a specific word, but I see this as the applicable case for me. That’s why I was asking to add the matches array to the apply filters function rather than updating it in the core plugin for each update or adding unnecessary queries.
Regarding the synonym option, the logic already overwrites the value in the wp_options table, this is related to the plugin as no one else uses the relevanssi synonyms option, I am not sure how it could be related to my site. I have already tested it and there is no duplication as the new value including the old synonyms +new synonyms overrwrites the old value containing the old synonyms only. If the user wants to delete any of the old synonyms he already has the old synonyms in the input in the synonymes tab on his admin dashboard, he can control it the way he likes rather than doing a mistake adding new synonyms without realising that it overwrites the old synonyms.
It could be that way in the synonyms tab:
<textarea name='relevanssi_synonyms' id='relevanssi_synonyms' rows='9' cols='60' value="”>
This will avoid overwriting and duplication of old values .
As I said, may be I am talking with a different approach as my site contains around 2500 posts and people usually search with statements or sentences and I shall need to add synonymes from time to time as per the analysis of user experience (they usually don’t search the exact words so I need to add synonyms based on their input).
I got your point regarding the duplication but this at least could be shown as an input value in the admin dashboard with the old values and sending the old and new values to the database.
Adding the $matches object to the filter doesn’t help, because the data you need is not in the $matches object.
I really don’t understand what you’re saying about the synonyms: you are describing the synonym system exactly the way it now works and your suggested change would not work correctly. If it works for you that way, fine, but I can’t change it, because the current code works the way the options are expected to work and your suggestion will make it impossible to ever remove synonyms. I’m not going to break that functionality.
I will check the issue regarding the $matches array when I have access to test tit.
Regarding the synonyms, I agree with you that adding it in the request function I posted above will cause duplication. To avoid overwriting the old synonyms, the text area could be modified that way in the synonyms-tab.php file:
This will avoid both overwriting and duplication of old values .
There’s no need to make changes: the current version works exactly as it should. Nothing is overwritten and duplicated.
Hi Mikko
Thanks for this awesome plugin, It works well on my website. Now I have a small problem when I want to enable a separate search box under a specific Category, This search box only searches for articles under this category, An example url for the search results page is “https://www.powerbigeek.com/dax/?s2=dax” the problem is it always a blank page no matter what word you search for. If I disable the plugin, it works . so do you know how to modify the plugin so that category search and plugin search do not conflict?
thanks!
Ryan, part of the problem might be the search term parameter: Relevanssi is looking for the search term in “s”, not “s2”.
I am using a WordPress service provided by my university, they have their own WordPress platform.
The problem is: Search results works for all posts but not pages. No matter if the keyword is present in the page or not, full length page is displayed. For the posts, I search, only 30 words are shown as per the settings, but this is not the case with the pages.
Please help me with this. Not sure, where is the problem, is it with the theme or the service? The only control I have is with the website, and if I have specific info on the back-end then it could be changed too by special request.
Anshul, the problem is likely in your theme. The theme is set so that an excerpt is shown for the posts, and the full post for the pages. To fix this, the search results template in the theme should be changed so that it shows excerpts for pages.
Hi,
I have a quick question.
I’m looking for products (woocommerce) associated with keywords inserted in articles related with ACF.
For example, I created an article with the title ADDICTION and in this article I added the terms :
– chocolate
– cigarette
– sex
– foods
etc
When my customer enters: “I like chocolate too much”, I’d like to list all the products associated with ADDICTION, without displaying the article ADDICTION, only the products
Currently, when I enter “I like chocolate too much”, only the article ADDICTION appears …
Do you have any idea how I can display the products and not the related article?
Thanks in advance for your help
Francis, if you want the search results to only show products, add the
post_type
parameter to the search and set the value toproduct
. Then the search will only show you products.Thank you very much for your prompt return!
I’ve been searching a little bit everywhere to understand how to filter with post_type, but I confess I’m lost, I don’t know Relevanssi well, nor the development code of Worpress. Do you have an example of a post_type filter?
Thanks again for your feedback
Francis
Francis, most WooCommerce themes add the post type parameter automatically and actually make it hard to search for anything else. If you use the Relevanssi shortcode to create the search form, this is easy:
[searchform post_type="product"]
If you use the default search form in your theme, editing it is harder, and requires changes to your site templates.If you want all your searches to only return products, the easiest solution is to make Relevanssi only index products. That way nothing else can ever come up as a search result.
Hello,
I have set Relevanssi to only search products, and it is working great, thank you very much for your excellent work.
I would like also to add, in the blog sidebar, a facility to search only within blog posts.
I added a block with [searchform post_type="post"] inside, but it is returning no results, even if posts are added to the index
Thank you
Mauro
Mauro, that’s how it would work. I would look to see if your theme is adding post type constraints in the search. What does the Relevanssi query look like? (Here’s how you can check) Does the Relevanssi admin search work?
Hey Mikko,
First of all, thanks for building this plugin. I absolutely love it.
We’re looking at enable one-letter searches so I added the one lister filter hook to the plugin code and it worked. But the problem is that when we update the plugin, then that code will be deleted correct? Is there any way around this where we can somehow add that code permanently and not have to go through re-adding it again every time we update the Relevanssi plugin?
Many thanks,
Habib.
Habib, do not touch the plugin files. Add the code to your theme functions.php, where it will be safe through plugin updates.
I have 2 suggestions to this page:
1) Maybe a typo?
In the changelog of free version 4.7.2.1 the filter relevanssi_custom_field_value was added at 4.0.3 not like this page saying since 2.0.3.
2) relevanssi_custom_fields_to_index – filter missing
I was unable to find the filter relevanssi_custom_fields_to_index in the free version 4.7.2.1, but found relevanssi_index_custom_fields that may be the right one, but then the docs may also need to fix the parameter list according to the changelog by adding a second parameter that contains the post ID
/**
* Filters the list of custom fields to index before indexing.
*
* @param array $custom_fields List of custom field names.
* @param int $post_id The post ID.
*/
$custom_fields = apply_filters( 'relevanssi_index_custom_fields', $custom_fields, $post_id );
1. Not a typo, the filter was introduced in Premium 2.0.3.
2. Yeah, that’s a typo, I’ll fix that.
How can I exclude certain ACF flexible content blocks from the search? The relevanssi_index_custom_fields filter does not work(
Maksim, the easiest method is to go to the flexible block settings in ACF and check the “Exclude from Relevanssi index” setting for the flexible content block. Then rebuild the index, and the field will be excluded.
I there hook for when a new attachment is added to the index?
I cant seem to find that specific hook.
Thanks!
Leighton, what is your goal? What are you trying to achieve with the hook? Relevanssi uses the WordPress action hook
wp_after_insert_post
to react to new posts.I’m using Algolia search and would like to add the attachment to Algolia’s index after it has been indexed and had it’s content read by relevanssi.
Relevanssi reads the attachments using the WP hook
add_attachment
on priority 10. If you run your code later on the same hook, you will be able to access the PDF contents.Hello. Is it possible to exclude a certain block on the page from the search? For example, by block class or in php code?
For example exclude the third section:
1
2
3
section 1
section 2
section class:noindex 3
Maksim, yes. You can give the block the CSS class
relevanssi_noindex
, and Relevanssi will ignore it. There’s also therelevanssi_block_to_render
filter hook you can use.How do I use the ‘relevanssi_user_searches_query_url’ filter hook? I’d like to change the search URL from using the query “?s=search_term” and instead have a custom URL like “/search/search_term”. Can this hook help me do this?
MattBCC, you don’t need Relevanssi hooks for that. WordPress supports that automatically. You can force that with these instructions from WPBeginner.