Created
February 24, 2023 05:42
-
-
Save shivapoudel/693df6f32921c68a6909be5e5a32faab to your computer and use it in GitHub Desktop.
Redirect homepage depending on country code.
This file contains 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 // Do not include this if already open! | |
/** | |
* Return the country code. | |
* | |
* @since 1.0.0 | |
*/ | |
function get_user_country_code() { | |
return 'GB'; // This is main United Kingdom front page. | |
} | |
/** | |
* Check either landing pages is in view. | |
* | |
* All landing page should exists with country code slug. | |
* | |
* @since 1.0.0 | |
* | |
* @return bool Is landing page exists? | |
*/ | |
if ( ! function_exists( 'is_landing_page_exists' ) ) { | |
function is_landing_page_exists() { | |
return is_page( array_map( 'strtolower', ['FR', 'BE', 'DE', 'IE', 'NL', 'CH', 'SE'] ) ); | |
} | |
} | |
/** | |
* Redirect homepage depending on country code. | |
* | |
* @since 1.0.0 | |
*/ | |
function mytheme_change_homepage_by_country_code() { | |
global $wp; | |
if ( ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' ) ) { | |
$country_code = get_user_country_code(); | |
if ( ( 'GB' === $country_code && ! is_front_page() ) && is_landing_page_exists() ) { | |
wp_safe_redirect( home_url() ); | |
exit; | |
} elseif ( ( 'GB' !== $country_code && is_front_page() ) || ( is_landing_page_exists() && $wp->request !== strtolower( $country_code ) ) ) { | |
wp_safe_redirect( home_url( sprintf( '/%s/', strtolower( $country_code ) ) ) ); | |
exit; | |
} | |
} | |
} | |
add_action( 'template_redirect', 'mytheme_change_homepage_by_country_code' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment