I have a client with a private portal who needed to block all traffic from non-USA IP addresses for spam purposes.
The site is hosted on Cloudways which offers a GeoIP feature built in, but turning it on does nothing by itself.
After digging through Cloudways documentation for setting up GeoIP and inputting some queries into WPCodey, I finally got a working code snippet.
Here is the code that worked for me. You can change the ‘Access denied’ message to anything you want. I chose to keep it vague.
Simple add this in as a code snippet via WPCodey* or functions.php and viola!
To test it was working, I used this tool: https://geotargetly.com/geo-browse
$FORWARDED_COUNTRY = getenv('HTTP_X_FORWARDED_COUNTRY');
if ($FORWARDED_COUNTRY !== 'United States') {
// Block traffic
wp_die('Access denied.');
}
*Affiliate link
Cloudways documentation link: https://support.cloudways.com/en/articles/5126366-how-to-use-geoip-with-your-application#h_158df011dc