Home > Mobile >  Wordpress wp_redirect only once for users from Country
Wordpress wp_redirect only once for users from Country

Time:01-12

Trying to achieve a situation on a Wordpress site:

  • when user is from countrycode EE then redirect him to url /et but only do it once so the user could still visit the original language as well /

Added my code into the functions php with an add_action but I get an infinite loop My code is as follows:

function wpml_lang_redirect() {

    if(isset($_SERVER["MM_COUNTRY_CODE"])){
        //If it is exists, use it.
        $userCountry = $_SERVER["MM_COUNTRY_CODE"];
        //$euroCountry = array('EE');
    
        if( $userCountry == 'EE' ) {
            wp_redirect( get_bloginfo('url') . "/et/" );
            //wp_redirect( get_bloginfo('url') . "?lang=en" );
            exit;
        } 
    }
}
add_action( 'template_redirect', 'wpml_lang_redirect' );

I also don't want to put this on the homepage as I want to redirect users once but still be able to switch to the original homepage for ENG content.

Currently a bit confused how could this be even achieved? or would this rather be something to .htaccess type of assignment and not PHP?

CodePudding user response:

Here's the solution with PHP, with setting a cookie

if( !isset($_COOKIE["first_time_estonia"]) ){
    $browser_lang = $_SERVER["MM_COUNTRY_CODE"]; // from server provider
    setcookie("first_time_estonia", "1", time()   24 * 3600, "/", "", 0); // for 24hrs

    if( !isset($_COOKIE["first_time_estonia"]) ){   
        header("Reload:0"); // has been here in 24hrs doesn't redirect again
    }
    if ($browser_lang == 'EE') {
        header("Location: /et"); // hasn't been in 24hrs redirects to Estonian
    }
} 
  • Related