6

I know this question has been asked so many times but I didn't find any working solution or example which I can use to fix my problem.

I have been working on a client site. There are two similar sites, one for their own country and second for other country's visitors.

Their main site hosted in the root of the server and second site hosted in the subfolder.

Now what I want is a dynamic URL rewrite for the second site which is hosted into a subfolder with the country code of the visiting user.

For e.g.

http://example.com
http://example.com/subfolder/

are the URLs.

I want this http://example.com/subfolder/ to be changed into this http://example.com/country_code/ where country_code is visitor country code in ISO format getting through PHP function.

So if the user is from United States the subfolder must be changed into us, the new URL should be now http://example.com/us/.

I want this to work for all types of pages, whether its a page, post, category, tag or author page.

So again, http://example.com/subfolder/any-type-of-url/ => http://example.com/country_code/any-type-of-url/

Remember country_code is user/visitor country code in ISO format.

Let me know if someone needs more information on this. Thanks in Advance.

PS: I tried to achieve this using add_rewrite_rule() function available in WP.

10
  • how you get the country code in htaccess?
    – Sagar V
    Jul 4, 2017 at 9:55
  • @SagarV I am not getting country code in .htaccess file, I have PHP function for it, btw I can get country code in .htaccess file too, see the answer here Jul 4, 2017 at 12:22
  • Are they really going to host the same site for each seperate country? Why do you not use qTranslate X or WPML? You can do URL rewriting there exactly as described.
    – Blackbam
    Jul 4, 2017 at 12:33
  • 1
    @Blackbam they are not hosting multiple sites, the site is designed to serve multiple country users. Read my question clearly, it says I want to rewrite subfolder with visitor country ISO code. If I use qTranslateX or WPML, it will not rewrite subfolder with country ISO code, it will just append to subfolder, like this /subfolder/in/. Btw translation plugins are not required in our case. I hope its clear now. Jul 4, 2017 at 12:41
  • 1
    Folder name present in the hosting can be named anything, "subfolder" for example and the visitors should be able to access the site with their respective country codes. Example : example.com/us/blog & example.com/in/blog both these URLs will call example.com/subfolder/blog. Correct me If I am wrong ? Jul 6, 2017 at 8:56

2 Answers 2

0

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 them
foreach ( $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' );
2
  • Will it replace subfolder with user country code? Jul 11, 2017 at 6:16
  • Not getting results what I supposed to get. Jul 11, 2017 at 7:37
0

.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 +FollowSymLinks
RewriteEngine on

#INDIA
RewriteCond %{HTTP:CF-IPCountry} ^IN$
RewriteRule !^in/ /in%{REQUEST_URI} [NC,NE,R,L]

#USA
RewriteCond %{HTTP:CF-IPCountry} ^US$
RewriteRule !^us/ /us%{REQUEST_URI} [NC,NE,R,L]

#THAILAND
RewriteCond %{HTTP:CF-IPCountry} ^TH$
RewriteRule !^th/ /th%{REQUEST_URI} [NC,NE,R,L]

This will replace

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

In case you want to use GeoIP

GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat

RewriteEngine on

#INDIA
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^IN$
RewriteRule !^in/ /in%{REQUEST_URI} [NC,NE,R,L]

#USA
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^US$
RewriteRule !^us/ /us%{REQUEST_URI} [NC,NE,R,L]

#THAILAND
RewriteCond %{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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.