0

I am using Wordpress with a Geo Target plugin, the intended behavior is that if a site visitor is in Germany, they are redirected to the German version of the website and have an option to click a link to view the English version. I am doing this by setting a session cookie to ignore the redirect on the homepage if they have already been sent to the German version. The issue I am having is that it is ignoring part of the if statement for $redirectedBefore and always redirecting to /de/. Here is the code I have:

<?php
require( dirname( FILE ) . '/wp-load.php' );
$country = do_shortcode( '[geoip-country]' );
//echo "Country: " . $country . "<br />";
//This does work and outputs the correct country code at the top of the homepage

if (isset($_COOKIE) && isset($_COOKIE['langPref'])){
$redirectedBefore = true;
} else {
$redirectedBefore = false;
}

if ( $country == ( 'DE' ) && !$redirectedBefore ) {
//header("Set-Cookie: langPref=1; expires=0; path=/;");
//Trying a couple ways to set cookie
setcookie("langPref", "1", 0, "/");
header("Location: /de/");
exit;
} else {
//header("Set-Cookie: langPref=1; expires=0; path=/;");
//Trying a couple ways to set cookie
setcookie("langPref", "1", 0, "/");
}
?>

Thank you in advance

Robert
  • 143
  • 14
  • 1
    do_shortcode runs after headers are sent: https://wordpress.stackexchange.com/questions/166028/headers-already-sent-when-i-try-to-add-headers-via-a-shortcode so you can't use the shortcode there. – Howard E Sep 17 '21 at 17:11
  • 1
    @HowardE, I think that is only true for shortcodes that run inside of `the_content` filter. Manually invoking `do_shortcode` should return normally. – Chris Haas Sep 17 '21 at 17:41
  • 1
    @Robert, PHP doesn't "ignore" parts of an `if` statement, they are just false. For every value that you are testing, perform a `var_dump` on the value to see what's in there. Never trust `echo` either, you always want to see what PHP sees. – Chris Haas Sep 17 '21 at 17:44

0 Answers0