Sorting Products by Custom Meta Fields

Shares

add_filter( ‘woocommerce_shortcode_products_query’, ‘woocommerce_shortcode_products_orderby’ );

function woocommerce_shortcode_products_orderby( $args ) {

$standard_array = array(‘menu_order’,’title’,’date’,’rand’,’id’);

if( isset( $args[‘orderby’] ) && !in_array( $args[‘orderby’], $standard_array ) ) {

$args[‘meta_key’] = $args[‘orderby’];

$args[‘orderby’]  = ‘meta_value_num’;

}

return $args;

}