Created
February 3, 2022 09:18
-
-
Save kagg-design/8d6810282c3da1008e816463dcec0c65 to your computer and use it in GitHub Desktop.
WPML redirect from /?lang= to /lang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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