Reputation: 447
I got this code that for some reason is not fully working, although it seems im on the right direction, and i have a guess on why is it not working, eventhough i dont know how to fix.
The ide is so if the HTTP_REFERER = a web containing the word example, and you are not loged it, then redirect you to mysite.com/login
add_action( 'init', 'example_redirect');
function metorik_redirect() {
if (!is_user_logged_in() && strpos($_SERVER['HTTP_REFERER'], "example")){
wp_redirect( site_url('/login/') );
exit;
}
}
The rule above seems to be triggering when conditions are met, but then it returns ERR_TOO_MANY_REDIRECTS
My guess is that it keeps finding the referer to be example everytime it loops through that function and then it never gets out of it. As stated, is just a guess.
UPDATE 1: I have tried with this other code i found in here stackoverflow, with same results:
add_action('template_redirect', 'redirect_if_example');
function redirect_if_example(){
if ( !is_user_logged_in() && coming_from_example(wp_get_referer()) ){
wp_safe_redirect( "/login/" );
exit;
} else{
wp_safe_redirect( get_home_url() );
exit;
}
}
function coming_from_example($url_string){
if ($url_string){
$url = parse_url($url_string);
return strpos($url['host'], 'example.com');
} else {
return false;
}
}
Thanks Kind regards
Upvotes: 0
Views: 328
Reputation: 1423
Try to redirect in correct hook and use correct strpos function like this: (this code should be in your functions.php file)
add_action( 'template_redirect', 'example_redirect');
function example_redirect() {
if (!is_user_logged_in() && strpos($_SERVER['HTTP_REFERER'], "example") !== false){
wp_redirect( wp_login_url() );
exit;
}
}
Also please make sure you are actually comming from website which has example
string in it.
Upvotes: 1