add_action( 'parse_request', 'wpse_395638_1' );
function wpse_395638_1( $wp ) {
// If the current URL doesn't have any path and with the www prefix, e.g.
// https://www.example.com or https://www.example.com/?foo=bar, then we
// completely disable the canonical redirect by unhooking redirect_canonical().
if ( empty( $wp->request ) ) {
$host = parse_url( home_url(), PHP_URL_HOST );
if ( "www.$host" === $_SERVER['SERVER_NAME'] ) {
remove_action( 'template_redirect', 'redirect_canonical' );
}
}
}
// This snippet doesn't disable canonical redirect, but the snippet ensures
// that the redirect URL uses the www prefix, unless the current URL doesn't
// use it.
add_filter( 'redirect_canonical', 'wpse_395638_2', 10, 2 );
function wpse_395638_2( $redirect_url, $requested_url ) {
$host = parse_url( $redirect_url, PHP_URL_HOST );
$host2 = parse_url( $requested_url, PHP_URL_HOST );
// If the current URL uses www, we add it back to the redirect URL.
if ( "www.$host" === $host2 ) {
$redirect_url = preg_replace( '#^http(s?)://#', 'http$1://www.', $redirect_url );
}
return $redirect_url;
}