如果您将设置domain.com
为的别名original.com
,则在WordPress中您无需执行任何操作即可使其工作。
问题是countrary:一旦DNS的2个域别名,每一个你的WordPress的URL将通过用户定义的域访问:domain.com/any/wp/url
,而且 domain2.com/any/wp/url
,domain3.com/any/wp/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网址:
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);
}
至此,您只为服务器设置了DNS,其中所有用户定义的域都是原始服务器的别名。
请注意,代码未经测试。