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