Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active September 21, 2020 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/a1acbd83071341989cd3f8e0d1cbd2f9 to your computer and use it in GitHub Desktop.
Save xnau/a1acbd83071341989cd3f8e0d1cbd2f9 to your computer and use it in GitHub Desktop.
Shows how to find the optgroup of a field value in a Participants Database custom template.
<?php
$record = new PDb_Template( $this );
// name of the field you're interested in
$field = 'interests';
// get the array of defined options
$option_list = $record->get_field_prop( $field, 'options' );
// assume the title is blank at first
$optgroup_title = '';
$value_title = '';
// scan through the options, holding on to the last option title
foreach( $option_list as $title => $value ) {
if ( $value === 'optgroup' ) {
$optgroup_title = $title;
continue; // continue to the next option
}
// if the value matches, break and keep the last option title
if ( $value === $record->get_value( $field ) ) {
$value_title = $title;
break; // we found it, break out of the loop
}
}
// shows the result
echo $optgroup_title . ':' . $value_title;
@xnau
Copy link
Author

xnau commented Sep 21, 2020

Note that this will not work as expected with multi-select type fields because the saved value is going to be an array.

If you want to do this with a multi-select, you can get the first value from the saved values with:

current( $record->get_value( $field ) )

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