I don’t know if this can be done at once —using maybe an htaccess rule–.
But, I think rebuilding the existing rewrite rules instead of adding new ones can do the trick.
There are filters available for each group of rewrite rules:
post_rewrite_rules
date_rewrite_rules
comments_rewrite_rules
search_rewrite_rules
author_rewrite_rules
page_rewrite_rules
{post_type}_rewrite_rules
{taxonomy}_rewrite_rules
By using ‘post_rewrite_rules’ filter we can rebuild the post rewrite rules using a code like this:
add_filter('post_rewrite_rules', function($rules){
$newRules = [];
/**
* Loop through the current set of rules and:
* 1- Prepend the language matching regex
* 2- Increment the current matched groups by one each
* 3- Append the matched language to the query as the matched group 1
* 4- Add the modified rule to the $newRules array
*/
foreach ($rules as $regex => $query) {
$newRules['^([a-z]{2})/' . $regex]
= str_replace(
['[2]', '[1]'],
['[3]', '[2]'], $query) . '&lang=$matches[1]';
}
return $newRules;
});
For the changes to be applied; rewrite rules should be flushed. Also the post permalink should be modified by adding the current language to it, may be using a code like this:
add_filter('post_link', function ($link){
$lang = get_query_var('lang', 'en');
return
str_replace(
home_url("https://wordpress.stackexchange.com/"),
home_url("https://wordpress.stackexchange.com/" . $lang . "https://wordpress.stackexchange.com/"),
$link
);
});