I’m trying to sort my WooCommerce Shop Page/homepage by a custom field (like_amount) in descending order. “Like_amount” contains the number of likes a product has, but some products do not have likes.
The current code I have works when I visit https://example.com/?orderby=like_amount, or select the “Sort by Likes” option I created. However, it does not work when I visit the homepage (which is also the Shop page) or any product archive/product category pages.
My suspicion is that it has something to do with the meta_key being empty for some posts.
So, any idea 1) why it isn’t working and 2) how I can ensure posts are displayed even if the meta_key is empty? Thanks in advance!
add_filter( 'woocommerce_get_catalog_ordering_args', 'ya_custom_product_sorting' );
function ya_custom_product_sorting( $args ) {
if( isset( $_GET['orderby'] ) && 'like_amount' === $_GET['orderby'] ) {
$args['meta_key'] = 'like_amount';
$args['orderby'] = array( 'meta_value_num' => 'DESC' );
}
return $args;
}