我有一个WordPress儿童主题,我使用php文件作为特定页面的模板。
我正在尝试为名为GeoIP Detection的插件实现API。请参阅下面我在我的网站上使用的PHP文件。我试图应用的API是"重定向取决于国家"位于here
当我加载脚本时,我应该被重定向到https://www.google.com.sg
但是,它不会这样做。
谢谢。
我的PHP
<?php /* Template Name: GeoIPDetectionv3 */
add_action('template_redirect', 'geoip_redirect', 5);
function geoip_redirect(){
if (is_admin())
return;
// This condition prevents a redirect loop:
// Redirect only if the home page is called. Change this condition to the specific page or URL you need.
if (!is_page(90))
return;
if (!function_exists('geoip_detect2_get_info_from_current_ip'))
return;
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
switch ($countryCode) {
case 'DE':
$url = '/germany';
break;
case 'US':
$url = '/usa';
break;
case 'SG':
$url = 'https://www.google.com.sg';
break;
default:
$url = 'https://www.google.com.sg';
}
if ($url) {
wp_redirect(get_current_blog_id(null, $url));
exit;
}
}
答案 0 :(得分:2)
使用单个PHP标记,并确保代码的最后部分实际上在PHP标记内。目前它不是,因此它被解析为纯文本。
更新:我已经为您清理了一下并更新了代码以反映您修改过的问题;即,遵循我们的评论。
<?php /* Template Name: GeoIPDetectionv3 */
add_action('template_redirect', 'geoip_redirect', 5);
function geoip_redirect(){
if ( is_admin() ) {
return; // Not applicable.
}
if ( 123 !== get_current_blog_id() ) {
return; // Not on blog ID 123.
}
if ( ! is_page( 90 ) ) {
return; // Not a specific page ID on this blog.
}
if ( ! function_exists( 'geoip_detect2_get_info_from_current_ip' ) ) {
return;
}
$userInfo = geoip_detect2_get_info_from_current_ip();
$countryCode = $userInfo->country->isoCode;
switch ($countryCode) {
case 'DE':
$redirect_to = '/germany';
break;
case 'US':
$redirect_to = '/usa';
break;
case 'SG':
$redirect_to = 'https://www.google.com.sg';
break;
default:
$redirect_to = 'https://www.google.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;
}
}