How to Block Any USA Region from accessing Your WordPress Site
Sometimes, you might need to block any USA region or any region in the world from accessing your WordPress site for many reasons. Why I’m writing this, because recently one of my client wanted me to help him block two USA states i.e., Pennsylvania and Michigan. So I made a JavaScript code where I used third-party geolocation API to achieve this. We can use same JS code in WordPress by creating a function.
Block US Regions from accessing Your WordPress Site
To create a WordPress function that blocks access to your site from specific states like Pennsylvania and Michigan, you can use a combination of PHP and JavaScript. We’ll add a custom function to your theme’s functions.php file that enqueues a JavaScript file and handles the geolocation logic.
Step-by-Step Guide
// Function to block access based on state
function blockStates() {
// Fetch the visitor's IP information
fetch('https://ipinfo.io/json?token=YOUR_TOKEN_HERE')
.then(response => response.json())
.then(data => {
console.log(data); // Log the data for debugging purposes
// Extract the state information
const region = data.region;
// List of blocked states
const blockedStates = ['Pennsylvania', 'Michigan'];
// Check if the visitor is from a blocked state
if (blockedStates.includes(region)) {
document.title = "Access Denied";
document.body.innerHTML = '<h1>Access Denied</h1><p>We are sorry, but access to this website is not available from your location.</p>';
}
})
.catch(error => {
console.error('Error fetching the IP information:', error);
});
}
// Call the function to block states
blockStates();
Add the function to enqueue the JavaScript file
Open your theme’s functions.php file or use snippets plugin to activate the following function:
function enqueue_block_states_script() {
// Register and enqueue the script
wp_register_script('block-states', get_template_directory_uri() . '/block-states.js', array(), null, true);
wp_enqueue_script('block-states');
}
add_action('wp_enqueue_scripts', 'enqueue_block_states_script');
By following these steps, you can effectively block users from Pennsylvania and Michigan from accessing your WordPress site.