HasteDesign / Registrations-for-WooCommerce

Add a registration product type to your WooCommerce installation.
GNU General Public License v2.0
38 stars 16 forks source link

Date order in admin overrides WooCommerce variation order #41

Closed mtruitt closed 5 years ago

mtruitt commented 5 years ago

Problem is below. Dates force frontend to display in order dates are in via the admin and does not honor the actual variation order.

image

image

So in this example it will always display May, March, Feb, July

Though my variation order is March, Feb, July, May.

mtruitt commented 5 years ago

Closing this as I found a way around it.

ajlowndes commented 4 years ago

hey mtruitt how did you find a way around this? I am battling the same issue and I cannot for the life of me figure out how to change the order of the dates in the front end dropdown.

ajlowndes commented 4 years ago

found this "sort alphabetically" snippet here: https://wordpress.org/support/topic/changing-the-order-of-variations/

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();
});