Howdy Waqas!
We use GeoIP on our marketing site, here’s how we call GeoIP directly in our theme code:
if ( class_exists( 'WPEngine\GeoIp' ) ) {
$geo = WPEngine\GeoIp::instance();
$country = $geo->country();
}
switch ($country) {
case 'CA':
# code...
break;
default:
# code...
break;
}
We do recommend having a default case to catch any cases where GeoIP couldn’t determine a country, or otherwise gives back unexpected content. You can of course define this in a custom function in your theme to make calling it inline more semantic.
Oops, one change to to ensure your function doesn’t throw an error if GeoIP gets disabled:
$country = null;
if ( class_exists( 'WPEngine\GeoIp' ) ) {
$geo = WPEngine\GeoIp::instance();
$country = $geo->country();
}
switch ($country) {
case 'CA':
# code...
break;
default:
# code...
break;
}
Thread Starter
Waqas
(@waqaslone)
Hi,
It worked like charm. Thanks for your prompt help.
Also, the approach you suggested and the one I was using earlier, which one of these is better in terms of the performance?
Regards,
Waqas
Realistically there won’t be any real noticeable performance difference between these, the method we recommended is slightly safer as it ensures that GeoIP is properly instantiated and the plugin is running. Because GeoIP runs server side and works with our caching layer, there should not be any real performance degradation when using GeoIP.
Thread Starter
Waqas
(@waqaslone)
great. Thanks for your help.