php - 使用 PHP 在 WordPress 中使用国家代码动态重写子文件夹

标签 php wordpress .htaccess url url-rewriting

我知道这个问题已被问过很多次,但我没有找到任何可用于解决我的问题的有效解决方案或示例。

我一直在为客户网站工作。有两个类似的网站,一个是针对他们自己的国家,另一个是针对其他国家的访问者。

他们的主站点托管在服务器的根目录中,第二个站点托管在子文件夹中。

现在我想要的是第二个站点的动态 URL 重写,该站点托管在带有访问用户国家/地区代码的子文件夹中。

例如

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

是 URL。

我希望将此 http://example.com/subfolder/ 更改为此 http://example.com/country_code/ 其中 country_code 是通过PHP函数得到的ISO格式的访客国家代码。

因此,如果用户来自美国,则子文件夹 必须更改为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 格式的用户/访问者国家/地区代码。

如果有人需要这方面的更多信息,请告诉我。提前致谢。

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

关于php - 使用 PHP 在 WordPress 中使用国家代码动态重写子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44701811/

相关文章:

php - mod_rewrite 和 apache clean 超链接

php - 对 CodeIgniter 中的对象和类感到困惑?

php - 在 WordPress 中使用回调键传递参数

javascript - 隐藏产品描述页面中的第一个缩略图

wordpress - 通过 WooCommerce 中的 ID 获取所选的运输方式标题

javascript - $.post 不能与 $J = jQuery.noConflict(); 结合使用

php - Prestashop 注册错误

php - 在这种情况下 &(与号)符号是什么意思?

apache - 如何在 .htaccess 文件中添加 "X-Frame-Options" header 以防止 'ClickJacking' 攻击

.htaccess - 多个 url 托管只有一个需要 https