Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Enhance: Bring back user to 1st page when filters are changed #9952

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions assets/js/utils/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@ export function getUrlParameter( name: string ) {
*/
export function changeUrl( newUrl: string ) {
if ( filteringForPhpTemplate ) {
/**
* We want to remove page number from URL whenever filters are changed.
* This will move the user to the first page of results.
*
* There are following page number formats:
* 1. query-{number}-page={number} (ex. query-1-page=2)
* - ref: https://github.com/WordPress/gutenberg/blob/5693a62214b6c76d3dc5f3f69d8aad187748af79/packages/block-library/src/query-pagination-numbers/index.php#L18
* 2. query-page={number} (ex. query-page=2)
* - ref: same as above
* 3. page/{number} (ex. page/2) (Default WordPress pagination format)
*/
newUrl = newUrl.replace(
/(?:query-(?:\d+-)?page=(\d+))|(?:page\/(\d+))/g,
''
);

/**
* If the URL ends with '?', we remove the trailing '?' from the URL.
* The trailing '?' in a URL is unnecessary and can cause the page to
* reload, which can negatively affect performance. By removing the '?',
* we prevent this unnecessary reload. This is safe to do even if there
* are query parameters, as they will not be affected by the removal
* of a trailing '?'.
*/
if ( newUrl.endsWith( '?' ) ) {
newUrl = newUrl.slice( 0, -1 );
}

window.location.href = newUrl;
} else {
window.history.replaceState( {}, '', newUrl );
Expand Down