如何在WordPress中设置动态“主页”和“网站URL”


How to set dynamic `home` and `siteurl` in WordPress?

我使用locale过滤器动态配置多语言设置。获取子域名以确定语言。

function load_custom_language($locale) {
    // get the locale code according to the sub-domain name.
    // en.mysite.com => return `en`
    // zh.mysite.com => return `zh_CN`
    // tw.mysite.com => return `zh_TW`
    // etc..
}
add_filter('locale', 'load_custom_language');

这适用于索引页面,但当我重定向到另一个页面时,由于homesiteurl的设置,它总是将我的网站重定向到原始网站(www.mysite.com)。

所以我很想找到一种动态的方法来根据请求过滤homesiteurl,因为我可能会为mysite使用多个子域,而这两种设置只有一个设置。

您可以覆盖wp-config.php文件中的管理设置。因此,如果你想要一些动态的东西,以下应该起作用:

//presumes server is set up to deliver over https
define('WP_SITEURL', 'https://' . $_SERVER['HTTP_HOST']);
define('WP_HOME', 'https://' . $_SERVER['HTTP_HOST']);

这需要在行之前添加

require_once(ABSPATH . 'wp-settings.php');

否则,您可能会遇到使用错误URL的某些内容的问题,尤其是主题文件。

我找到了另一种很好的方法来完成这项工作:

在检查了内核的源代码后,我发现每个选项上都有不同的过滤器option_xxx

因此,在我的任务中,我尝试使用option_siteurloption_home过滤器来保持要加载的选项,只是为了防止加载选项,并保持它所具有的SERVER_NAME

function replace_siteurl($val) {
    return 'http://'.$_SERVER['HTTP_HOST'];
}
add_filter('option_siteurl', 'replace_siteurl');
add_filter('option_home', 'replace_siteurl');

使用这种方式,它不需要更改wp_config.php文件,并且可以很容易地添加到主题或插件中。

要动态设置域和协议(httphttps),请使用:

// Identify the relevant protocol for the current request
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https" : "http";
// Set SITEURL and HOME using a dynamic protocol.
define('WP_SITEURL', $protocol . '://' . $_SERVER['HTTP_HOST']);
define('WP_HOME', $protocol . '://' . $_SERVER['HTTP_HOST']);
相关文章: