'How to get custom woocommerce variation price working with sort low to high

I've written some code so that on a woocommerce category page, depending on a custom field that is set on the category, it looks up the product variations and finds the cheapest variation that has a matching custom field.

I've used woocommerce_variable_price_html to get it to show on the frontend of the site but the sort low to high and high to low does not work with these prices.

How can I get them to work with these also? I assume the data is stored in a seperate place that the sort by low - high uses?

Part of the code is below that works it out and displays it.

add_filter( 'woocommerce_variable_sale_price_html', 'get_min_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'get_min_variation_price_format', 10, 2 );

function get_min_variation_price_format( $price, $product ) {
    if(is_product_category()) {
        $category = get_queried_object();
        $catid = $category->term_id;
        if(!empty(get_term_meta($category->term_id, 'wh_worktop_type', true))) {
            $worktop_type = strtolower(get_term_meta($category->term_id, 'wh_worktop_type', true));
        }
    }
    if(!empty($worktop_type)) {
        $min_variation_price = $product->get_variation_regular_price( 'min');
        $cheapestprice = 10000;
        foreach($product->get_children() as $thisvariation) {
            if(strtolower(get_post_meta($thisvariation, 'worktop_variation_type', true)) == $worktop_type && get_post_meta($thisvariation, '_price', true) < $cheapestprice) {
                $cheapestprice = get_post_meta($thisvariation, '_price', true);
            }
        }
    } else {
        //need to return normal from price
    }
    return wc_price($cheapestprice);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source