'Add sorting by stock quantity in WooCommerce products sort by

I have added the following code to my theme functions.php.

The "Availability" sort option does show up but when I select it, it is sorted by Title, not stock quantity.

I also tried using stock_quantity as a meta_key (even though it's not a meta) and that didn't work either.

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'availability' == $orderby_value ) {
        $args['orderby'] = 'stock_quantity';
        $args['order'] = 'DESC';
        $args['meta_key'] = '';
    }
    return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['availability'] = 'Availability';
    return $sortby;
}


Sources

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

Source: Stack Overflow

Solution Source