Linas Vildziunas
Linas Vildziunas

Reputation: 171

Redirect page based on the referrer in Wordpress

I am looking for a simple solution to redirect visitors who are trying to visit /order/ page from particular referrer to a page /order-2/.

Let's say, visitors are coming from facebook to my homepage, but I don't want facebook visitors to see page /order/, instead I want to redirect them to /order-2/, if that makes sense.

It is wordpress website, so I guess it should be easy to find a solution with a plugin, however I couldn't find anything that would work..

Thanks you for your help!

Upvotes: 2

Views: 5565

Answers (1)

vlasits
vlasits

Reputation: 2235

This ought to work. It checks the referrer url for facebook and redirects accordingly. I'm not 100% certain that wp_safe_redirect will work with a relative url. This code would go into your functions.php:

add_action('template_redirect', 'redirect_if_facebook');
function redirect_if_facebook(){
    if ( is_page('order') && coming_from_facebook(wp_get_referer()) ){
         wp_safe_redirect( "/order-2/" );
         exit;
     } else{
          wp_safe_redirect( get_home_url() );
          exit;
     }
}

function coming_from_facebook($url_string){
   if ($url_string){
      $url = parse_url($url_string);
      return strpos($url['host'], 'facebook.com');
   } else {
     return false;
   }
}
?>

Upvotes: 1

Related Questions