Skip to content

Instantly share code, notes, and snippets.

@mtruitt
Created April 25, 2019 17:59
Show Gist options
  • Select an option

  • Save mtruitt/c908e90641018059da47cb6f3e43c653 to your computer and use it in GitHub Desktop.

Select an option

Save mtruitt/c908e90641018059da47cb6f3e43c653 to your computer and use it in GitHub Desktop.
Alphabetical order for variation dropdowns
<?php
add_filter('woocommerce_dropdown_variation_attribute_options_html', function ($html) {
$xml = simplexml_load_string($html);
$select = array('id' => (string)$xml->attributes()['id'],
'name' => (string)$xml->attributes()['name'],
'attribute_name' => (string)$xml->attributes()['data-attribute_name'],
'show_option_none' => (string)$xml->attributes()['data-show_option_none']);
$options = array();
foreach($xml->option as $option) {
$options[] = array('text' => (string)$option,
'value' => (string)$option->attributes()['value'],
'selected' => (string)$option->attributes()['selected'] === 'selected');
}
usort($options, function ($a, $b) {
return strcmp($a['value'], $b['value']);
});
$xml = simplexml_load_string('<select/>');
$xml->addAttribute("id", $select["id"]);
$xml->addAttribute("name", $select["name"]);
$xml->addAttribute("data-attribute_name", $select["attribute_name"]);
$xml->addAttribute("data-show_option_none", $select["show_option_none"]);
foreach ($options as $option) {
$child = $xml->addChild('option');
$child->value = $option['text'];
$child->addAttribute('value', $option['value']);
if ($option['selected']) {
$child->addAttribute('selected', 'selected');
}
}
return $xml->asXML();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment