WordPress (Woocommerce) order by Product Dimensions (Length, Width, and then Height)

I am attempting to order my products by Length and Width, where it sorts by length first and, if two products have the same value, it will sort by Width (and so on). I would like to add height if I can get this working first.

So far the issue I’m running into is that it orders the products by length and only length (plus a bug where even the length is incorrect, i.e. the product order is 2.1, 2, and 2.5).

This is as far as I’ve gotten with the query:

function woocommerce_catalog_orderby( $args ) {
    $args['meta_query'] = array(
        'relation' => 'AND',
        'length_clause' => array(
            'key'     => '_length',
            'type' => 'DECIMAL',
            'orderby' => 'meta_value_num',
        ),
        'width_clause' => array(
            'key'     => '_width',
            'type' => 'DECIMAL',
            'orderby' => 'meta_value_num',
        ),
    );

    $args['orderby'] = array(
        'length_clause' => 'ASC',
        'width_clause' => 'ASC',
    );

    return $args;
}
add_filter('woocommerce_get_catalog_ordering_args', 'woocommerce_catalog_orderby');

I’m convinced I’m missing something obvious that I just can’t see at the moment. Any help is much appreciated!

Leave a Comment