10up / ElasticPress

A fast and flexible search and query engine for WordPress.
https://elasticpress.io
GNU General Public License v2.0
1.25k stars 313 forks source link

Autosuggest: Allow multiple input search fields with different queries for post types #2135

Open fagiani opened 3 years ago

fagiani commented 3 years ago

Is your enhancement related to a problem? Please describe.

The problem I'm currently facing is that I was unable to find a way to have multiple search fields that are capable of querying specific/different post types in the search.

Describe the solution you'd like

A way to be able to adjust the query before autosuggest fetch based on the input field information (like id, class, etc).

Designs

Add a check for a window function just like epDataFilter to allow query customization before fetching the results.

Describe alternatives you've considered

Any other implementation that requires less effort or that is already implemented and is just not on the sight atm would be highly considered.

Additional context

With this abstraction not only the post types would be customizable but pretty much anything within the query.

fagiani commented 3 years ago

While the #2136 PR is being evaluated. It is possible to use the following workaround:

Given you have those two input fields within your page:

...
<!-- This is the main/default search field -->
<input type="search" id="defaultSearch">
...
<!-- This is the custom search field -->
<input type="search" id="customSearch">
...

you could use the following JS to enable custom query:

    var epCustomInput = false;
    window.epas.customQuery = "{\"from\":0,\"size\":5,\"sort\":[...],...}}}";
    const {fetch: whatwgFetch} = window;
    window.fetch = async (...args) => {
      if (window.epCustomInput) {
        const { customQuery, placeholder } = window.epas;
        const replacement = document.getElementById(window.epCustomInput).value;
        args[1].body = customQuery.replace(new RegExp(placeholder.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), replacement);
      }
      return await whatwgFetch(...args);
    }

    var epSearchInputs = document.getElementsByTagName("input");
    for ( i=0; i < epSearchInputs.length; i++ ) {
      if (epSearchInputs[i].type == "search") {
        epSearchInputs[i].addEventListener("focus", function() {
          if(this.id == "defaultSearch") {
            window.epCustomInput = false;
          } else {
            window.epCustomInput = this.id;
          }
        });
      }
    }

Hopefully that can become useful to others in the future!

JakePT commented 3 years ago

The specific use case of limiting autosuggest results to a particular post type is addressed by #1689