如何在WordPress中设置自定义Permalink,实现无sub-domains的多国家站点
How to Add Country-Code Prefixes to WordPress Permalinks (No Subdomains)
Absolutely, your goal is totally achievable! You don’t need subdomains to build a multi-country site with country-code prefixed URLs—here are two reliable ways to make this work:
Option 1: Use a Multilingual/Regional Plugin (Easiest for Beginners)
Plugins like Polylang (free) or WPML (premium) are built for exactly this use case, and they handle all permalink rewrites automatically:
- Install and activate your chosen plugin.
- For Polylang: Navigate to
Languages > Settings, then under the "URL modifications" section, select "Prepend the language code to all URLs". - Replace default language codes (like
en) with your preferred country codes (e.g.,us,gb,fr). - Save your settings, then go to
Settings > Permalinksand click "Save Changes" to refresh WordPress’s rewrite rules.
This will automatically add the country code prefix to every URL on your site—homepage, posts, categories, and pages included.
Option 2: Manual Code Customization (For Developers)
If you’d rather avoid plugins, you can add custom code to your theme’s functions.php file (or a dedicated custom plugin) to implement this:
- Register a custom query variable for the country code:
function add_country_code_query_var($vars) { $vars[] = 'country_code'; return $vars; } add_filter('query_vars', 'add_country_code_query_var');
- Add rewrite rules to handle the country-code prefix:
function add_country_code_rewrite_rules() { // Rule for country-code prefixed homepage add_rewrite_rule('^([a-z]{2})/?$', 'index.php?country_code=$matches[1]', 'top'); // Rule for posts/categories with country code prefix add_rewrite_rule('^([a-z]{2})/(.+)?$', 'index.php?country_code=$matches[1]&$matches[2]', 'top'); } add_action('init', 'add_country_code_rewrite_rules');
- Update your permalink structure in
Settings > Permalinksto something like/%country_code%/%category%/%postname%/(adjust the rewrite rules above if you need a different structure). - Don’t forget to click "Save Changes" in the Permalinks settings to flush the rewrite rules—this is critical for the new URLs to work.
Important Notes
- Double-check that your country codes (e.g.,
us,de) don’t conflict with existing category slugs or page URLs—this could trigger 404 errors. - Test thoroughly after setup: Visit URLs like
https://example.com/us/andhttps://example.com/us/category/post-linkto confirm they load correctly. - If you use a caching plugin, clear your cache after making these changes to ensure old URL structures aren’t served.
内容的提问来源于stack exchange,提问作者Qarar Ul Hassan
相关产品推荐
相关产品推荐

