How to Execute Custom Code for Specific Country in WordPress
Вставка
- Опубліковано 6 лют 2025
- In this wordpress tutorial for beginners you will learn how to add php custom snippet / code for specific country in wordpress website. So custom code will run / insert for country like US (united states) / UK / PK etc. user or customer in wordpress.
** Use this Custom Code & Customize according to your requirement.
// Function to get the user's country code
function get_user_country() {
// Get the user's IP address
$ip = $_SERVER['REMOTE_ADDR'];
// Use ip-api.com to get the country information
$response = wp_remote_get("ip-api.com/json/{$ip}");
if (is_wp_error($response)) {
return null; // Handle error
}
$data = json_decode(wp_remote_retrieve_body($response), true);
// Check if the request was successful
if ($data['status'] === 'success') {
return $data['countryCode']; // Returns the country code (e.g., 'US', 'CH')
}
return null; // Handle case where country code is not found
}
// Function to execute code based on the user's country
function execute_code_based_on_country() {
$country_code = get_user_country(); // Get the user's country code
if ($country_code === 'US') { // Check if the user is from United States
// Your PHP code for US users
echo "Welcome, US user!";
}
}
// Hook the function to an appropriate action
add_action('wp', 'execute_code_based_on_country');
#php #country #user #phpcode #countries #users #snippet #wpcode #wordpress #wordpresstutorial #webtaskwithhassan #hassangilani