Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nextab/ea5de2cff5a423acc11e3be09d31824b to your computer and use it in GitHub Desktop.
Save nextab/ea5de2cff5a423acc11e3be09d31824b to your computer and use it in GitHub Desktop.
// Enqueue the script on the booking page
function zmmt_payment_enqueue_script() {
$temp_user_data = get_user_meta(get_current_user_id());
$user_data = array_map(function ($item) {
return $item[0];
}, $temp_user_data);
// Filter out all user data that we don't need
$keysToKeep = [
'nickname',
'first_name',
'last_name',
'zmmt_',
];
$user_data = array_filter($user_data, function ($key) use ($keysToKeep) {
foreach ($keysToKeep as $partialKey) {
if (strpos($key, $partialKey) !== false) {
return true;
}
}
return false;
}, ARRAY_FILTER_USE_KEY);
// Localize the script with your data
wp_enqueue_script('zmmt-payment'); // this needs to happen first!!!
wp_localize_script('zmmt-payment', 'zmmtPersonalData', $user_data); // here we are passing the array $user_data (from PHP) to JavaScript; can be used in JavaScript with window.zmmtPersonalData
}
add_action('wp_enqueue_scripts', 'zmmt_payment_enqueue_script', 9999);
/* Example Use in JavaScript => we are running over the inputs in a repeater field for a JetForm and fill them with variables from the passed user object that correspond in name */
if (window.zmmtPersonalData) {
// Get the first row
const firstRow = document.querySelector('div[name="zmmt_event_orders"] .jet-form-builder-repeater__row');
if (firstRow) {
firstRow.setAttribute('data-personal-row', 'true');
// Find all input and select elements within the first row
const inputElements = firstRow.querySelectorAll('.jet-form-builder-repeater__row-fields input[data-field-name], .jet-form-builder-repeater__row-fields select[data-field-name]');
// console.log(inputElements);
inputElements.forEach(element => {
const fieldName = element.getAttribute('data-field-name');
// Check if the fieldName exists in zmmtPersonalData
if (zmmtPersonalData.hasOwnProperty(fieldName)) {
element.value = zmmtPersonalData[fieldName];
triggerEvent(element, 'change');
}
});
triggerChangeButtons();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment