Add language/country code to each possible URL

I’m working on a similar solution right now – the website must have language codes in all URLs (except the default language), but only pages are translatable in a way WPML/Polylang plugins do it. For news (blog) we just show posts in particular language (they are separate, not translations of each other). All the other content is mixed in all languages. Also, the UI is displayed in a language set from URL too.

Here’s what I did to get those rewrite rules prepended with language codes:

function prepend_default_rewrite_rules( $rules ) {

    // Prepare for new rules
    $new_rules = [];

    // Set up languages, except default one
    $language_slugs = ['ar', 'ku'];

    // Generate language slug regex
    $languages_slug = '(?:' . implode( "https://wordpress.stackexchange.com/"', $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( "https://wordpress.stackexchange.com/"', $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' );

Haven’t tested it to full extent – just came up with the solution after studying the WP_Rewrite class. So it’s a work in progress. Hope it helps though.

P.S.: Also, I would be happy to see your solution for “I retrieve the value from the URL to determine the language/country = complete” – that’s what I’m currently working on 🙂

Leave a Comment