diff --git a/lib/experimental/blocks.php b/lib/experimental/blocks.php index 28203a2009850..cab6d2ef84443 100644 --- a/lib/experimental/blocks.php +++ b/lib/experimental/blocks.php @@ -150,3 +150,32 @@ function gutenberg_block_core_query_add_url_filtering( $query, $block ) { return $query; } add_filter( 'query_loop_block_query_vars', 'gutenberg_block_core_query_add_url_filtering', 10, 2 ); + +function gutenberg_block_core_query_add_search_query_filtering( $query ) { + + // if the query is not the main query, return + if ( $query->is_admin() || ! $query->is_main_query() ) { + return; + } + + // Check if the instant search gutenberg experiment is enabled + $gutenberg_experiments = get_option( 'gutenberg-experiments' ); + $instant_search_enabled = $gutenberg_experiments && array_key_exists( 'gutenberg-search-query-block', $gutenberg_experiments ); + if ( ! $instant_search_enabled ) { + return; + } + + // Get the search key from the URL + $search_key = 'instant-search'; + if ( ! isset( $_GET[ $search_key ] ) ) { + return; + } + + // Add the search parameter to the query + $query->set( 's', sanitize_text_field( $_GET[ $search_key ] ) ); +} + +add_action( + 'pre_get_posts', + 'gutenberg_block_core_query_add_search_query_filtering' +); diff --git a/packages/block-library/src/search/index.php b/packages/block-library/src/search/index.php index c0eb88a528d5d..91f193c78a1b9 100644 --- a/packages/block-library/src/search/index.php +++ b/packages/block-library/src/search/index.php @@ -208,8 +208,8 @@ function render_block_core_search( $attributes, $content, $block ) { } if ( $enhanced_pagination && $instant_search_enabled && isset( $block->context['queryId'] ) ) { - - $search = ''; + $is_inherited = isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] && ! empty( $block->context['queryId'] ); + $search = ''; // If the query is defined in the block context, use it if ( isset( $block->context['query']['search'] ) && '' !== $block->context['query']['search'] ) { @@ -217,13 +217,18 @@ function render_block_core_search( $attributes, $content, $block ) { } // If the query is defined in the URL, it overrides the block context value if defined - $search = empty( $_GET[ 'instant-search-' . $block->context['queryId'] ] ) ? $search : sanitize_text_field( $_GET[ 'instant-search-' . $block->context['queryId'] ] ); + if ( $is_inherited ) { + $search = empty( $_GET['instant-search'] ) ? '' : sanitize_text_field( $_GET['instant-search'] ); + } else { + $search = empty( $_GET[ 'instant-search-' . $block->context['queryId'] ] ) ? '' : sanitize_text_field( $_GET[ 'instant-search-' . $block->context['queryId'] ] ); + } $form_context = array_merge( $form_context, array( - 'search' => $search, - 'queryId' => $block->context['queryId'], + 'search' => $search, + 'queryId' => $block->context['queryId'], + 'isInherited' => $is_inherited, ) ); }