Skip to content

Instantly share code, notes, and snippets.

@dave-mills
Last active September 28, 2020 08:05
Show Gist options
  • Save dave-mills/8dbaaffbfb016fcf4a9f8ecc50e89e5e to your computer and use it in GitHub Desktop.
Save dave-mills/8dbaaffbfb016fcf4a9f8ecc50e89e5e to your computer and use it in GitHub Desktop.
Example Callback function for Ultimate Member dropdown field
function getCities() {
//get the value from the 'parent' field, sent via the AJAX post.
$choice = $_POST['parent_option'];
//Depending on the value of $choice, return a different array.
switch($choice) {
case "France":
$cities = [
"Paris" =>"Paris",
"Marseille" => "Marseille",
"Lyon" => "Lyon"
];
break;
case "Spain":
$cities = [
"Madrid"=>"Madrid",
"Barcelona"=>"Barcelona"
];
break;
default:
//code to do something if other options are not selected (throw an error, or set $cities to a default array)
$cities = ["no city"];
}
return $cities;
}
@jzeisloft
Copy link

In case it helps anyone else coming here to figure this out:

  1. The parent and child fields must be “Dropdown” field types; not just any field can provide a parent value

  2. If you need to populate a dropdown based on a field that is not a type that supports being a "parent option", you’ll need to write some custom js to capture the input value and assign it to a dummy/hidden single-option dropdown that can be used as the parent - e.g.:

$('#user_email').on( "focusout", function() {
	var domain = $(this).val().replace(/.*@/, "");
	$('select[name="email_domain"]').append($('<option></option>').attr('selected', 'selected').attr('val', domain).text(domain));
	$('select[name="email_domain"]').trigger('change'); // a change to this element is what triggers the ajax call
});
  1. The callback to populate the options list will then be able to access the Email Domain parent value - e.g. (in the callback):



$domain = $_POST['parent_option'];


  1. 400 error on the POST? I also had to add a kludgy “nopriv” action into my own functions file (based on the auth version in the plugin code) because I was using this in the registration form, when the user is not yet logged in - e.g.:
if(function_exists('UM')) {
    add_action('wp_ajax_nopriv_um_select_options', array(UM()->form(), 'ajax_select_options'));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment