Rewrite sub folder dynamically with country code in WordPress using PHP Rewrite sub folder dynamically with country code in WordPress using PHP wordpress wordpress

Rewrite sub folder dynamically with country code in WordPress using PHP


You can do it by pretending rewrite rules through filter, based on user country ISO code. Please find code below.

function prepend_default_rewrite_rules( $rules ) {// Prepare for new rules$new_rules = [];// Set up languages, except default one, get user language code$user = get_current_user_id();  $language_slugs = (array) get_user_meta($user->ID, 'country_code');// Generate language slug regex$languages_slug = '(?:' . implode( '/|', $language_slugs ) . '/)?';// Set up the list of rules that don't need to be prefixed$whitelist = [    '^wp-json/?$',    '^wp-json/(.*)?',    '^index.php/wp-json/?$',    '^index.php/wp-json/(.*)?'];// Set up the new rule for home page$new_rules['(?:' . implode( '/|', $language_slugs ) . ')/?$'] = 'index.php';// Loop through old rules and modify themforeach ( $rules as $key => $rule ) {    // Re-add those whitelisted rules without modification    if ( in_array( $key, $whitelist ) ) {        $new_rules[ $key ] = $rule;    // Update rules starting with ^ symbol    } elseif ( substr( $key, 0, 1 ) === '^' ) {         $new_rules[ $languages_slug . substr( $key, 1 ) ] = $rule;    // Update other rules    } else {        $new_rules[ $languages_slug . $key ] = $rule;    }} // Return out new rules return $new_rules;}add_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' );


.htaccess would be faster way to achieve this and won't have issue with users implemented full page cache too.

If you are using cloudflare on your website, you can use the following simple code in which we get country from cloudflare itself ;)

Options +FollowSymLinksRewriteEngine on#INDIARewriteCond %{HTTP:CF-IPCountry} ^IN$RewriteRule !^in/ /in%{REQUEST_URI} [NC,NE,R,L]#USARewriteCond %{HTTP:CF-IPCountry} ^US$RewriteRule !^us/ /us%{REQUEST_URI} [NC,NE,R,L]#THAILANDRewriteCond %{HTTP:CF-IPCountry} ^TH$RewriteRule !^th/ /th%{REQUEST_URI} [NC,NE,R,L]

This will replace

xyz.com/sg/randomtoxyz.com/us/random if the user is from USA.

In case you want to use GeoIP

GeoIPEnable OnGeoIPDBFile /path/to/GeoIP.datRewriteEngine on#INDIARewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$RewriteRule !^in/ /in%{REQUEST_URI} [NC,NE,R,L]#USARewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$RewriteRule !^us/ /us%{REQUEST_URI} [NC,NE,R,L]#THAILANDRewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^TH$RewriteRule !^th/ /th%{REQUEST_URI} [NC,NE,R,L]

You can always add more countries as per your use case. In someone is still looking for a PHP code too, just let me know.

For PHP based in Wordpress

 //For fetching url eg. xyz.com/in/  from xyz.com/in/random-link/abc $current_url = home_url( add_query_arg( NULL, NULL ) ); //For fetching random-link/abc $current_rel_url = str_replace( home_url(), "", $current_url ); // I am using cloudflare country variable here , you can use any of your api or whatever method needed if( !empty($_SERVER["HTTP_CF_IPCOUNTRY"]) ) {    $userCountry = $_SERVER["HTTP_CF_IPCOUNTRY"];    exit( wp_safe_redirect( site_url() . $userCountry . $current_rel_url ) );  }

You can modify redirect condition as per your use case.