Sort 1 meta value by DESC and the other 2 by ASC
-
Hi, was wondering if anybody could clarify how to specify multiple ordering methods for the WooCommerce archive pages.
I’ve created a sorting method using
woocommerce_catalog_orderby
which I have named “custom_sorting”. I would like this function to basically combine the default sorting with sorting by popularity. Ideally I would like the first 4 products to be sorted by newness and the rest by popularity, but I don’t think this is possible, so we’ve settled for sorting by popularity and menu_order and we’ll manually set the products that should appear before the others.Here is the code I have so far:
function theme_get_catalog_ordering_args( $args ) { $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); if ( 'custom_sorting' == $orderby_value ) { $args['meta_key'] = 'total_sales'; //$args['orderby'] = 'popularity'; $args['orderby'] = 'meta_value menu_order title'; $args['order'] = array([0] => 'DESC', [1] => 'ASC'); } return $args; }
What i’ve done is crudely combined the wp_query requests of both “default sorting” and the “sort by popularity” methods to create what I am wanting. However, according to the wp_query, “menu_value” should be sorted DESC while “menu_order” should be sorted ASC. My results are close but currently both fields are being sorted either ASC or DESC depending on what I set for
$args['order']
. I tried setting that value to an array as you see above, as well as “DESC ASC ASC” and “DESC, ASC, ASC”. Nothing seems to change it from sorting all fields by the same thing.Here is my wp_query request:
wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC, wp_posts.menu_order DESC, wp_posts.post_title DESC LIMIT 0, 20
As you can see, wp_postmeta.meta_value (which actually should be “wp_postmeta.meta_value+0” but I don’t know how to set that) is being sorted DESC while “wp_posts.menu_order” is being incorrectly sorted DESC.
Any suggestions?
- The topic ‘Sort 1 meta value by DESC and the other 2 by ASC’ is closed to new replies.