Monday, July 10, 2017

Rewrite sub folder dynamically with country code in WordPress using PHP

Leave a Comment

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 Answers

Answers 1

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' ); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment