I want to GROUP BY my Woocommerce products on archive & category pages according to the custom field value called group_id. If there are products with the same group_id value, I want to list only one of them. How can I do it?
I tried this but it doesn’t work.
function custom_grouped_products_query( $q ) {
if ( is_product_category() ) {
global $wpdb;
$q->query_vars['meta_query'][] = array(
'relation' => 'OR',
array(
'key' => 'group_id',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'group_id',
'compare' => 'EXISTS',
),
);
$q->set( 'orderby', 'meta_value' );
$q->set( 'order', 'ASC' );
$q->set( 'meta_key', 'group_id' );
$q->set( 'posts_per_page', -1 );
$q->set( 'post_type', 'product' );
$q->set( 'suppress_filters', false );
add_filter( 'posts_clauses', 'custom_grouped_products_clauses', 10, 2 );
}
}
add_action( 'woocommerce_product_query', 'custom_grouped_products_query' );
function custom_grouped_products_clauses( $clauses, $q ) {
global $wpdb;
$clauses['groupby'] = "{$wpdb->postmeta}.meta_value";
return $clauses;
}
2
Answers
Its not tested but maybe something like this ?