Home / Admin / Restrict WordPress Admin Access by Country
Duplicate Snippet

Embed Snippet on Your Site

Restrict WordPress Admin Access by Country

Restrict access to wp-admin based on visitor country using Cloudflare's country header. Useful for agencies, membership sites, and business websites that only allow administrators from specific regions.

Installation:
Add this snippet as a PHP Snippet in WPCode and set it to Auto Insert → Run Everywhere.

Requirements:
Your website should be behind Cloudflare so the CF-IPCountry header is available.

Default Allowed Countries:
United States (US)
United Kingdom (GB)
India (IN)

You can modify the allowed country list inside the code.

Code Preview
php
<?php
<?php
/**
 * Snippet: Restrict WordPress Admin Access by Country
 * Description: Allows wp-admin access only from approved countries.
 *
 * Curated by: Avijit Datta
 * Agency: CypraWeb Digital
 * Website: https://cyprawebdigital.com
 *
 * Version: 1.0
 */
add_action('admin_init', 'cwd_country_based_admin_restriction');
function cwd_country_based_admin_restriction() {
    if (!is_user_logged_in()) {
        return;
    }
    if (!current_user_can('manage_options')) {
        return;
    }
    if (!isset($_SERVER['HTTP_CF_IPCOUNTRY'])) {
        return;
    }
    $allowed_countries = array(
        'US',
        'GB',
        'IN'
    );
    $visitor_country = strtoupper(
        sanitize_text_field($_SERVER['HTTP_CF_IPCOUNTRY'])
    );
    if (!in_array($visitor_country, $allowed_countries, true)) {
        wp_die(
            sprintf(
                'Admin access is restricted from your location (%s).',
                esc_html($visitor_country)
            ),
            'Access Restricted',
            array(
                'response' => 403
            )
        );
    }
}

Comments

Add a Comment