Skip to content

Instantly share code, notes, and snippets.

@Qubadi
Created May 2, 2024 10:11
Show Gist options
  • Save Qubadi/ac7a99a26331afc8b38c69a9ea3c570d to your computer and use it in GitHub Desktop.
Save Qubadi/ac7a99a26331afc8b38c69a9ea3c570d to your computer and use it in GitHub Desktop.
Jetformbuilder form, A custom code for auto detect country and land code phone ( New style and new version ).
1. Start by creating a new PHP snippet. Paste your custom code into it and set it to run "everywhere".
2. Create a text field, set the type to "tel", and name the form field "phone".
3. Create a select field, set it to "manual input" (do not add any options), and name the form field "country".
4. Create a hidden field named "full_phone_number" for storing the full phone number.
5. Create another hidden field named "full_country_name" for storing the full country name.
6. Add both hidden fields to the "Post Submit Action" section under "Content".
7. Update the page slug name to the specific page where you have added the form. For instance, if
the current page slug name is "contact", change it to match the URL of the page where the form is placed.
8. Finally, register for an account at https://ipinfo.io/signup ,to obtain a token key. Then,
integrate the token into your fetch request as follows: fetch('https://ipinfo.io?token=YOUR_TOKEN_KEY_HERE').
_______________________________________________________
function include_country_dropdown_scripts() {
global $post;
if (is_a($post, 'WP_Post') && $post->post_name === 'contact') {
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
<style>
/* Isolate styles from affecting outside of the intl-tel-input */
#phone {
width: 100%; /* Full width to match other form inputs */
}
.iti {
width: 100%; /* Ensure the container does not exceed the input field width */
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const input = document.querySelector("#phone");
const countryDropdown = document.getElementById('country');
// Initialize international telephone input
const iti = intlTelInput(input, {
separateDialCode: true,
geoIpLookup: function(callback) {
fetch('https://ipinfo.io?token=YOUR_TOKEN_KEY_HERE')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch IP info');
}
return response.json();
})
.then(data => {
if (data && data.country) {
callback(data.country.toLowerCase());
} else {
throw new Error('Country data missing in response');
}
})
.catch(error => {
console.error('Error in geoIpLookup:', error.message);
callback('us'); // Default to 'us' if there's an error
});
},
initialCountry: "auto",
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
});
// Populate the country dropdown
fetch('https://restcountries.com/v3.1/all')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch countries');
}
return response.json();
})
.then(data => {
data.sort((a, b) => a.name.common.localeCompare(b.name.common));
data.forEach(country => {
const option = document.createElement('option');
option.value = country.cca2;
option.textContent = `${country.name.common} (${country.cca2})`;
countryDropdown.appendChild(option);
});
syncCountrySelection();
})
.catch(error => {
console.error('Error loading countries:', error.message);
});
// Sync the country selection with the phone input
function syncCountrySelection() {
const countryData = iti.getSelectedCountryData();
if (countryData && countryData.iso2) {
countryDropdown.value = countryData.iso2.toUpperCase();
} else {
console.log('No valid country data available, defaulting to first option.');
countryDropdown.selectedIndex = 0;
iti.setCountry(countryDropdown.value.toLowerCase());
}
}
countryDropdown.addEventListener('change', (e) => {
iti.setCountry(e.target.value.toLowerCase());
});
input.addEventListener('countrychange', syncCountrySelection);
// Ensure the full phone number with land code and the full country name are included in the form data
const form = document.querySelector('form');
form.addEventListener('submit', function() {
const fullPhoneNumber = document.createElement('input');
fullPhoneNumber.type = 'hidden';
fullPhoneNumber.name = 'full_phone_number';
fullPhoneNumber.value = iti.getNumber();
form.appendChild(fullPhoneNumber);
const fullCountryName = document.createElement('input');
fullCountryName.type = 'hidden';
fullCountryName.name = 'full_country_name';
fullCountryName.value = countryDropdown.options[countryDropdown.selectedIndex].text.match(/^.*?(?=\s*\()/)[0];
form.appendChild(fullCountryName);
});
});
</script>
<?php
}
}
add_action('wp_footer', 'include_country_dropdown_scripts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment