3

I'm running WordPress 6.0.1 and I'd like to achieve a smilingly easy thing, I have a query loop which shows posts that must be filtered by a query parameter so I can add a search box into the page.

I tried passing URL parameters like '?s=keyword_to_search_for' but it doesn't seem to be affected so I enabled the option "Inherit query from template" where the results should be affected by the global query configuration. My issue is that when that's enabled no posts are shown (while when it's disabled it shows all).

The query loop shows all my posts correctly with the pagination, I just want to put a search box above the list to be able to filter them through URL parameters.

Query Loop

Query Loop Settings

1 Answer 1

2

To avoid modifying the main query, you might consider adding a custom query variable with PHP:

add_filter( 'query_vars', function( $vars ) {
  $vars[] = 'qls'; // As query-loop-search.
  return $vars;
} );

and use ?qls=foo instead of ?s=foo.

To target the corresponding query loop, add the text :query-loop-search into the search box of the query loop block in the editor.

Then we could grab the value of the custom query variable ?qls=foo and set it as the search variable for the target query with a little more PHP:

add_action( 'pre_get_posts', function( \WP_Query $q ) {
    $qls = $q->get( 'qls' );
    if ( empty( $qls ) || is_admin() || $q->is_main_query() ) {
        return;
    }
    if ( $q->is_search() && ':query-loop-search' === trim( $q->get( 's' ) ) ) {
        $q->set( 's', $qls );
    }
} );

This should only apply for sub-queries (from query-loop blocks) on the front-end.

Note that this is untested.

Another approach could be to use Javascript and the built-in REST API to fetch data from a custom search input field.

2
  • Thanks for the reply, just one clarification, what is the "Inherit query from template" toggle for ? Commented Jul 22, 2022 at 16:28
  • This setting seems rather confusing to be honest, even after reading the docs here: wordpress.org/support/article/query-loop-block/…. Looking at the code this setting (when active) seems to pick up the query variables from the main query and use it in the sub-query used in the query loop block: github.com/WordPress/wordpress-develop/blob/… Commented Jul 22, 2022 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.