Preserved Query Strings and Hooks

The address bar URL is built in PHP and passed to the script, which only checks it is on the same origin and calls history.replaceState(). The rel="canonical" link in the head is never changed.

  1. Canonical URL: bp_get_canonical_url() on BuddyPress pages, wp_get_canonical_url() on single posts and pages, otherwise nothing. Any other page can supply one with the lh_canonicaliser_canonical_url filter; LH SEO Meta Tags uses it for a blog-index front page. With no canonical URL the script is not loaded.
  2. Preserved query strings: every preserved key present on the current request is added to the canonical URL, unless the canonical URL already has that key. Any other query string is dropped.
  3. Fragment and state: the script keeps the current #fragment and history.state, and does nothing if the URL already matches.

Preserved by default

KeysWhy
s, search, members_search, groups_searchSearch terms (WordPress and BuddyPress)
redirect_toWhere to go after logging in
replytocomOpens the comment reply form when JavaScript comment replies are unavailable
unapproved, moderation-hashLets a commenter see their own comment while it awaits moderation
preview, preview_id, preview_noncePost previews
_wpnonce, action, key, loginAction, confirmation and password reset links

Filters

add_filter( 'lh_canonicaliser_preserved_query_vars', function ( $keys ) {
	$keys[] = 'lang';
	return $keys;
} );

When the script loads

It is enqueued on wp_enqueue_scripts, deferred in the footer, so it works with block and classic themes and never runs on wp-login.php or in wp-admin. It is skipped on non-GET requests, embeds, previews, Customizer previews, feeds and robots.txt. The target URL reaches the script as window.lhCanonicaliser.url, printed inline before it.

Page caching

Preserved values are written into the page HTML. A key added through the filter must also be one the page cache varies on, or a cached page can show another visitor’s value in the address bar. The defaults are all keys that vary the cache or stop the page being cached.