wp-content » themes » functions.php » Disable WordPress comments based on User GeoLocation

Disable WordPress comments based on User GeoLocation

If you want to disable comments in WordPress based on the user’s location, you can do so by using the following steps:

Step 1. Install and activate the “GeoIP Detection” plugin. This plugin allows you to detect the user’s location based on their IP address.


Step 2. Add the following code to your theme’s functions.php file:

function df_disable_comments_based_on_location($open, $post_id) {
  // Replace XX with the two-letter country code for the location where you want to disable comments
  if (geoip_detect2_get_info_from_current_ip()->country->isoCode == 'XX') {
    return false;
  }
  return $open;
}
add_filter('comments_open', 'df_disable_comments_based_on_location', 20, 2);

This code will disable comments for users located in the country with the specified ISO code. You can add multiple countries by separating the ISO codes with a pipe (|) symbol, like this:

if (geoip_detect2_get_info_from_current_ip()->country->isoCode == 'XX|YY|ZZ') {
  return false;
}

Keep in mind that this method may not be completely reliable, as it relies on the accuracy of IP address geolocation data.

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended