Dynamically rewrite a subfolder with a country code in WordPress using PHP

I know this question has been asked so many times, but I have not found any working solution or example that I can use to fix my problem.

I work on a client site. There are two similar sites: one for your country, the second for visitors to other countries.

Their main site is located in the root of the server and the second site, located in a subfolder.

Now I want the dynamic url to be rewritten for the second site, which is located in a subfolder with the country code of the user who visited.

For instance,

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

are the urls.

I want this to http://example.com/subfolder/be changed to this http://example.com/country_code/, where country_codeis the visitor's country code in ISO format, passing through the php function.

, , subfolder us, URL- http://example.com/us/.

, , , , , .

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

country_code - / ISO.

, - . Advance.

PS: add_rewrite_rule(), WP.

+4
1

, , , ISO- . , .

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' );
0

Source: https://habr.com/ru/post/1679892/


All Articles