PHP Code for WordPress to manually show ads only in a specific country without plugin

By: Prof. Dr. Fazal Rehman | Last updated: February 3, 2024

How does it work? Step 1: Open the functions.php file of WordPress theme Step 2: Add the following code at the bottom of functions.php
function show_ads_in_specific_country() { $ip_address = $_SERVER[‘REMOTE_ADDR’]; $country_code = ‘PK’; // Replace ‘PK’ with the country code for the country where you want to show the ad $country = file_get_contents(“http://ip-api.com/json/$ip_address”); $country = json_decode($country); if ($country->countryCode == $country_code) { // Display your ad code here } } add_action(‘wp_head’, ‘show_ads_in_specific_country’);
  Note:   $country_code = ‘PK’; here you can change the country code where you want to see the advertisement. (visitor’s country codes are available on ipapi.com or ipdata.co) // Display your ad code here This is the place where you put your advertisement code
All Copyrights Reserved 2025 Reserved by T4Tutorials