我知道这个问题被问了很多次,但我没有找到任何可行的解决方案或示例,我可以用它来解决我的问题.
我一直在客户网站上工作.有两个类似的网站,一个用于自己的国家,第二个用于其他国家的访问者.
他们的主站点托管在服务器的根目录和托管在子文件夹中的第二个站点.
现在我想要的是第二个站点的动态URL重写,它被托管到具有访问用户的国家代码的子文件夹中.
对于例如
http://example.com
http://example.com/subfolder/
是网址.
我想将此http://example.com/subfolder/更改为此http://example.com/country_code/,其中country_code是ISO格式的访问者国家/地区代码,通过PHP函数.
因此,如果用户来自美国,则必须将子文件夹更改为我们,新的网址现在应该是http://example.com/us/.
我希望这适用于所有类型的页面,无论是页面,帖子,类别,标签还是作者页面.
再次,http://example.com/subfolder/any-type-of-url/ => http://example.com/country_code/any-type-of-url/
请记住,country_code是ISO格式的用户/访客国家/地区代码.
如果有人需要更多相关信息,请告诉我.提前致谢.
PS:我试图使用WP中提供的add_rewrite_rule()函数来实现这一点.
解决方法
您可以根据用户国家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,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' );