2

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.