WP Woocommerce Elementor custom query product_cat sorting

I am using elementor and woocommerce in WP, and I've build a page with the loopgrid widget, in it I have set up a loop that returns my product categories. By default the product categories only have name and ID, meaning by default I can only sort by either name and category. Using ACF fields I've added a number field named "num_sort". I know elementor has custom query filters with this guide https://developers.elementor.com/docs/hooks/custom-query-filter/ and I've tried using a simple function that fetches the value in "num_sort" that then I can insert in the widget. However it doesn't seem to work, which I'm certain I've done it wrong. function numberSorting( $query ) { $query->set( 'meta_key', 'num_sort' ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'order', 'ASC' ); } add_action( 'elementor/query/sort_by_number', 'numberSorting' );

Comment (1)

Jese Leos

August 24, 2024

Verified user

function numberSorting( $query ) { // Check if the query is for product categories if ( isset( $query->query['post_type'] ) && $query->query['post_type'] === 'product' && isset( $query->query['taxonomy'] ) && $query->query['taxonomy'] === 'product_cat' ) { $query->set( 'meta_key', 'num_sort' ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'order', 'ASC' ); } } add_action( 'elementor/query/sort_by_number', 'numberSorting' );

You’ll be in good company