You can use a shortcode to populate your options with three (3) important provisions:
- The shortcode should NOT include the normal square brackets (
[and]). So, instead of[my_shortcode key='value']you would usemy_shortcode key='value'. - Any parameters in the shortcode must use single quotes. That is:
my_shortcode key='value'and notmy_shortcode key="value" - Shortcodes should return a string value of HTML of
<option>and/or<optgroup>elements.
Note: your shortcode does not have to escape before returning (but it is recommended) because my plugin runs the output through the wp_kses() function before displaying on the page only allowing <optgroup> and <option> elements with the disabled and hidden attributes on both and additionally only value and selected attributes on the <option> elements and the label attribute on the <optgroup> elements.
Basic Example
Let’s say I want to create a dropdown of my WordPress plugins to choose from. I might create a shortcode in my active theme’s functions.php like this—it just has my services hardcoded as a string and returns it:
function au_get_plugins() {
$o = '<option value="controllable-fields">Controllable Fields</option>';
$o .= '<option value="accessible-reading">Accessible Reading</option>';
$o .= '<option value="dtx">CF7 - Dynamic Text Extension</option>';
return $o;
}
add_shortcode('get_plugins', 'au_get_plugins', 10, 0);
Then, I would enter my shortcode in the tag generator’s options textarea like this:
get_plugins
The tag generator will display it like this:
[select_controller plugin id:my-plugin "get_plugins"]
And on the frontend, you’ll see the options outputted as your shortcode
<select name="plugin" id="my-plugin" ...>
<option value="controllable-fields">Controllable Fields</option>
<option value="accessible-reading">Accessible Reading</option>
<option value="dtx">CF7 - Dynamic Text Extension</option>
</select>
Advanced Example
Let’s say I want to create a dropdown of my WordPress plugins to choose from, but not just a list of my plugins, but also grouped by their category. I might create a shortcode in my active theme’s functions.php like this:
function au_get_plugins() {
// TBA - Coming Soon
}
add_shortcode('get_plugins', 'au_get_plugins', 10, 0);
In this function, I’m pulling a list of all my products of the custom product post type. I then get its category taxonomy and create a multidimensional array. This will act as the basis of my option groups.
Finally, I loop through that multidimensional array to generate the HTML. I also want to pre-select the product if viewing that page and set it to readonly if that’s the case.
Then, I would enter my shortcode in the tag generator’s options textarea like this:
get_plugins
The tag generator will display it like this:
[select_controller plugin id:my-plugin "get_plugins"]
And on the frontend, you’ll see the options outputted as your shortcode
<select name="plugin" id="my-plugin" ...>
<!-- TBA - Coming Soon -->
</select>