如果您设置domain.com
作为的别名original.com
, 在WordPress中,您无需采取任何措施即可使其正常工作。
问题是数量:一旦在DNS中,这两个域就是别名,every WordPress的url可通过用户定义的域访问:domain.com/any/wp/url
, 而且domain2.com/any/wp/url
, domain3.com/any/wp/url
等等
所以,你要做的是
检查url是否为用户定义的域之一如果是,检查请求的页面是否为单数CPT及其授权保存域的页面如果不是,将请求重定向到原始域wp-config.php
define(\'ORIGINAL_DOMAIN\', \'original.com\');
现在,您可以轻松实现上述工作流:
add_action(\'template_redirect\', \'check_request_domain\', 1);
function check_request_domain() {
$domain = filter_input(INPUT_SERVER, \'HTTP_HOST\', FILTER_SANITIZE_URL);
// strip out the \'www.\' part if present
$domain = str_replace( \'www.\', \'\', $domain);
// if the request is from original domain do nothing
if ( $domain === ORIGINAL_DOMAIN ) return;
// if it is not a singular company CPT request redirect to same request
// but on original domain
if ( ! is_singular(\'company\') ) {
redirect_to_original(); // function defined below
}
// if we are here the request is from an user domain and for a singular company request
// let\'s check if the author of the post has user meta, assuming meta key is `\'domain\'`
// and the meta value is the same of domain in current url
$meta = get_user_meta( get_queried_object()->post_author, \'domain\', TRUE );
if ( $meta !== $domain ) { // meta doesn\'t match, redirect
redirect_to_original(); // function defined below
} else {
// meta match, only assuring that WordPress will not redirect canonical url
remove_filter(\'template_redirect\', \'redirect_canonical\');
}
}
现在,让我们编写一个函数,使用当前url重定向请求,但使用原始域
/**
* Redirect the request to same url, but using original domain
*/
function redirect_to_original() {
$original = untrailingslashit( home_url() ) . add_query_arg( array() );
wp_safe_redirect( $original, 301 );
exit();
}
最后要做的事情是过滤永久链接创建,以便将用户定义的域用于单个公司CPT URL:
add_filter( \'post_type_link\', \'custom_user_domain_plink\', 999, 2 );
function custom_user_domain_plink( $post_link, $post ) {
// we want change permalink only for company cpt posts
if ( $post->post_type !== \'company\' ) return $post_link;
// has the user setted a custom domain? If not, do nothing
$custom = get_user_meta( $post->post_author, \'domain\', TRUE );
if ( empty($custom) ) return $post_link;
// let\'s replace the original domain, with the custom one, and return new value
return str_replace( ORIGINAL_DOMAIN, $custom, $post_link);
}
At this point, you have only set DNS for your server, where all the user defined domains are aliases of the original.
请注意,代码未经测试。