2

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 countries visitors.

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

Now what I want is dynamic url rewrite for second site which is hosted into sub folder 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 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 type 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.

1 Answer 1

0

I think the most difficult part is to remove the subfolder part from the url with Wordpress website on both places.

What if you change subfolder name to international and change rewrite rules to have ISO codes before the urls?

So you would have:

To add the iso codes you try to do it by yourself using rewrite_rules_array filter or just use a translation plugin like Polylang that already add those codes automatically to the url and can even do browser language detection.

To do it by yourself I would do something like this: (very basic example)

function add_iso_codes_to_url( $rules ) {

    $new_rules = [];

    $iso_codes = '(?:us/|uk/)?';

    // home page
    $new_rules[$iso_codes . '/?$'] = 'index.php';

    // Change other rules
    foreach ( $rules as $key => $rule ) {

        if ( substr( $key, 0, 1 ) === '^' ) { 

            $new_rules[ $iso_codes . substr( $key, 1 ) ] = $rule;

        } else {

            $new_rules[ $iso_codes . $key ] = $rule;

        }
    }

    return $new_rules;
}
add_filter( 'rewrite_rules_array', 'add_iso_codes_to_url' );

Your Answer

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

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