我因为受不了香港地区的加载速度,现在添加了一个hk.motsuni.cn,在香港特区访问motsuni.cn的话就会跳转到hk,那么如何实现的?
我们只需要在functions.php中添加以下代码
function get_user_location_from_ip() { // 获取用户IP地址 $user_ip = $_SERVER['REMOTE_ADDR']; // 使用ipinfo.io获取地理位置信息 $url = "https://ipinfo.io/$user_ip/json"; $response = wp_remote_get($url); // 解析API响应并返回地理位置信息 if (!is_wp_error($response) && $response['response']['code'] === 200) { $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // 检查响应是否包含有效的地理位置信息 if (isset($data['country'])) { return $data['country']; } else { // 响应不包含有效的地理位置信息,返回空字符串 return ''; } } else { // 处理获取地理位置失败的情况 return ''; } } function redirect_to_hk_site() { // 获取用户地理位置信息 $user_location = get_user_location_from_ip(); // 如果用户地理位置为香港,进行重定向到香港站点 if ($user_location == 'HK') { $redirect_url = 'https://hk.motsuni.cn/';//改成你自己的站点 wp_redirect($redirect_url); exit; } } add_action('template_redirect', 'redirect_to_hk_site');
就可以实现这个跳转