Skip to content

Instantly share code, notes, and snippets.

@kagg-design
Created February 3, 2022 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kagg-design/8d6810282c3da1008e816463dcec0c65 to your computer and use it in GitHub Desktop.
Save kagg-design/8d6810282c3da1008e816463dcec0c65 to your computer and use it in GitHub Desktop.
WPML redirect from /?lang= to /lang
<?php
/**
* Redirect class file.
*
* @package wtei-core
*/
namespace WTEICore;
/**
* Class Redirect
*/
class Redirect {
/**
* Init class.
*/
public function init(): void {
add_action( 'template_redirect', [ $this, 'template_redirect' ] );
}
/**
* Redirect if old blog address is found.
*/
public function template_redirect(): void {
if ( is_admin() || ! is_404() ) {
return;
}
$url = isset( $_SERVER['REQUEST_URI'] ) ?
filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_STRING ) :
'';
if ( ! $url ) {
return;
}
$post_id = url_to_postid( $url );
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['lang'] ) ) {
$lang = filter_input( INPUT_GET, 'lang', FILTER_SANITIZE_STRING );
unset( $_GET['lang'] );
$post_id = apply_filters( 'wpml_object_id', $post_id, 'post', false, $lang );
}
if ( $post_id ) {
$new_url = add_query_arg( $_GET, get_permalink( $post_id ) );
if ( site_url() . $url !== $new_url ) {
wp_safe_redirect( $new_url, 301 );
exit;
}
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment