【发布时间】:2020-11-15 21:35:27
【问题描述】:
我正在处理一个 WordPress 网站要求,以便在用户位于某个国家/地区时将他们重定向到他们所在国家/地区的特定主页。
(我不得不通过 WP Ajax 执行此操作,因为全页缓存阻止它直接在实时托管环境中工作 - 我之前在函数中非常简单地执行此操作。 php 挂钩到 'init')。 em>
当我在标题模板的开头调用它时,这有效,但仅在显示当前页面内容之后。如果我可以在页面显示之前将其挂钩,那就太好了,例如喜欢使用钩子,例如:'wp_loaded'、'template_redirect',但 jQuery 需要可用...
这是我的代码。它需要进一步整理,但感谢任何关于如何在页面内容显示之前进行重定向的建议?
function invoke_county_redirection() {
ob_start();
?>
<script type="text/javascript">
var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>";
jQuery.post(ajax_url, {
'action': 'country_redirection',
}, function (response) {
// Set the cookie to say we're performing the redirect - this will flag it not to happen again
createCookie('redirected', 'true');
if (response != '') {
window.location.replace(response);
}
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
</script>
<?php
echo ob_get_clean();
return;
}
function country_redirection() {
$redirect_url = '';
if ( $_COOKIE['redirected'] !== 'true' ) {
/* declare empty result url */
$result['url'] = '';
/* Call on geoip plugin to get the country from their IP address */
$userInfo = geoip_detect2_get_info_from_current_ip();
$country_code = $userInfo->country->isoCode;
/* if we've retreived the country code for the current user */
if ( $country_code ) {
/* GET THE CORRECT REDIRECT URL IF APPLICABLE TO THE USER COUNTRY */
$redirect_url = get_country_url($country_code);
}
}
echo $redirect_url;
wp_die();
}
add_action( 'wp_ajax_nopriv_country_redirection', 'country_redirection' );
add_action( 'wp_ajax_country_redirection', 'country_redirection' );
【问题讨论】:
标签: ajax wordpress redirect caching cookies