这是修复致命错误并根据给定页面id重定向用户的示例代码。您可以进一步优化代码,如果所有页面的“DE”和“US”重定向保持不变,您可以跳过if ( is_page( 90 ) )
检查这些国家/地区代码。
add_action( \'template_redirect\', \'geoip_redirect\', 5 );
function geoip_redirect() {
//Return if not admin, or the blog id is not 123, or not on the specified page, or if the function doesn\'t exists
//List of pages to redirect from
$pages = array(
50,
90
);
//Return if not admin, or the blog id is not 123, or not on the specified page, or if the function doesn\'t exists
if ( is_admin() || 123 !== get_current_blog_id() || ! is_page( $pages ) || ! function_exists( \'geoip_detect2_get_info_from_current_ip\' ) ) {
return;
}
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
if ( is_page( 90 ) ) {
switch ( $countryCode ) {
case \'DE\':
$redirect_to = \'/germany\';
break;
case \'US\':
$redirect_to = \'/usa\';
break;
case \'SG\':
$redirect_to = \'www.google.com.sg\';
break;
default:
$redirect_to = \'www.google.com.sg\';
}
} elseif ( is_page( 50 ) ) {
//Change URL accordingly
switch ( $countryCode ) {
case \'DE\':
$redirect_to = \'/germany\';
break;
case \'US\':
$redirect_to = \'/usa\';
break;
case \'SG\':
$redirect_to = \'www.amazon.com.sg\';
break;
default:
$redirect_to = \'www.amazon.com.sg\';
}
//So on you can add additional else if conditions for rest of your pages
}
if ( ! empty( $redirect_to ) ) {
if ( stripos( $redirect_to, \'http\' ) === 0 ) {
wp_redirect( $redirect_to ); // Full URL.
} else {
wp_redirect( home_url( $redirect_to ) ); // Local /path.
}
exit;
}
}
如果重定向对“US”和“DE”保持不变,则此代码适用
add_action( \'template_redirect\', \'geoip_redirect\', 5 );
function geoip_redirect() {
//List of pages to redirect from
$pages = array(
50,
90
);
//Return if not admin, or the blog id is not 123, or not on the specified page, or if the function doesn\'t exists
if ( is_admin() || 123 !== get_current_blog_id() || ! is_page( $pages ) || ! function_exists( \'geoip_detect2_get_info_from_current_ip\' ) ) {
return;
}
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
if ( in_array( $countryCode, array( "US", "DE" ) ) ) {
$redirect_to = \'US\' == $countryCode ? \'/usa\' : \'/germany\';
} else {
if ( is_page( 90 ) ) {
switch ( $countryCode ) {
case \'SG\':
$redirect_to = \'www.google.com.sg\';
break;
default:
$redirect_to = \'www.google.com.sg\';
}
} elseif ( is_page( 50 ) ) {
//Change URL accordingly
switch ( $countryCode ) {
case \'SG\':
$redirect_to = \'www.amazon.com.sg\';
break;
default:
$redirect_to = \'www.amazon.com.sg\';
}
}
}
if ( ! empty( $redirect_to ) ) {
if ( stripos( $redirect_to, \'http\' ) === 0 ) {
wp_redirect( $redirect_to ); // Full URL.
} else {
wp_redirect( home_url( $redirect_to ) ); // Local /path.
}
exit;
}
}
好吧,您可以进一步优化代码,具体取决于15页的重定向值是多少,如果它们都相似的话,您肯定可以想出方法来最小化代码。