Skip to content

Commit

Permalink
Enhance search block functionality by integrating canonical URL suppo…
Browse files Browse the repository at this point in the history
…rt and updating interactivity configuration. This change allows the search block to utilize the canonical URL when performing instant searches.
  • Loading branch information
michalczaplinski committed Dec 9, 2024
1 parent a4d5b00 commit f4a6644
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
3 changes: 3 additions & 0 deletions packages/block-library/src/search/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';

Expand Down
38 changes: 28 additions & 10 deletions packages/block-library/src/search/view.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit f4a6644

Please sign in to comment.