Skip to content

Instantly share code, notes, and snippets.

@NickGreen
Last active November 22, 2021 02:25
Show Gist options
  • Save NickGreen/f8216df9740332f8e081da29415757ad to your computer and use it in GitHub Desktop.
Save NickGreen/f8216df9740332f8e081da29415757ad to your computer and use it in GitHub Desktop.
Pre-select drop-down item by value
<?php
function preselect_option() {
// URL should be in the format https://xxxxxxx/?option=VALUE_OF_OPTION
$option = htmlspecialchars($_GET["option"]);
echo '<script>';
echo 'function setSelectedIndex(s, valsearch) {';
echo ' // Loop through all the items in drop down list';
echo ' for (i = 0; i< s.options.length; i++) { ';
echo ' if (s.options[i].value == valsearch) {';
echo ' // Item is found. Set its property and exit';
echo ' s.options[i].selected = true;';
echo ' break;';
echo ' }';
echo ' }';
echo ' return;';
echo '}';
echo 'setSelectedIndex(document.getElementById("pa_plan"),"' . $option . '");';
echo '</script>';
}
add_action('wp_footer', 'preselect_option');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment