From f4a6644650f832dff8b3aa51f2e3babd080f7d0a Mon Sep 17 00:00:00 2001 From: Michal Czaplinski Date: Wed, 4 Dec 2024 17:07:14 +0000 Subject: [PATCH] Enhance search block functionality by integrating canonical URL support and updating interactivity configuration. This change allows the search block to utilize the canonical URL when performing instant searches. --- packages/block-library/src/search/index.php | 3 ++ packages/block-library/src/search/view.js | 38 +++++++++++++++------ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/block-library/src/search/index.php b/packages/block-library/src/search/index.php index 48883f76a43a82..8ff8aedae92a7c 100644 --- a/packages/block-library/src/search/index.php +++ b/packages/block-library/src/search/index.php @@ -210,6 +210,9 @@ function render_block_core_search( $attributes, $content, $block ) { } if ( $enhanced_pagination && $instant_search_enabled && isset( $block->context['queryId'] ) ) { + + wp_interactivity_config( 'core/search', array( 'canonicalURL' => get_permalink() ) ); + $is_inherited = isset( $block->context['query']['inherit'] ) && $block->context['query']['inherit'] && ! empty( $block->context['queryId'] ); $search = ''; diff --git a/packages/block-library/src/search/view.js b/packages/block-library/src/search/view.js index d280d355322afa..c9fa508335297b 100644 --- a/packages/block-library/src/search/view.js +++ b/packages/block-library/src/search/view.js @@ -1,7 +1,12 @@ /** * WordPress dependencies */ -import { store, getContext, getElement } from '@wordpress/interactivity'; +import { + store, + getContext, + getElement, + getConfig, +} from '@wordpress/interactivity'; /** @type {( () => void ) | null} */ let supersedePreviousSearch = null; @@ -110,18 +115,31 @@ const { state, actions } = store( return; } - const url = new URL( window.location.href ); + let url = new URL( window.location.href ); if ( value ) { - // Set the instant-search parameter using the query ID and search value - const queryId = ctx.queryId; - url.searchParams.set( - `instant-search-${ queryId }`, - value - ); + if ( ctx.isInherited ) { + // Get the canonical URL from the config + const { canonicalURL } = getConfig( 'core/search' ); + + // Make sure we reset the pagination. + url = new URL( canonicalURL ); + url.searchParams.set( 'instant-search', value ); + } else { + // Set the instant-search parameter using the query ID and search value + const queryId = ctx.queryId; + url.searchParams.set( + `instant-search-${ queryId }`, + value + ); - // Make sure we reset the pagination. - url.searchParams.set( `query-${ queryId }-page`, '1' ); + // Make sure we reset the pagination. + url.searchParams.set( `query-${ queryId }-page`, '1' ); + } + } else if ( ctx.isInherited ) { + // Reset global search for inherited queries + url.searchParams.delete( 'instant-search' ); + url.searchParams.delete( 'paged' ); } else { // Reset specific search for non-inherited queries url.searchParams.delete(