The following tax_query
returns only matched posts (with 'matchedstring' IN taxonomy array):
function only_returns_matched_posts( $query ) {
if( !$query->is_main_query() || is_admin() )
return;
$taxquery = array(
array(
'taxonomy' => 'mygroup',
'field' => 'slug',
'terms' => 'matchedstring',
'compare'=> 'IN'
)
);
$query->set( 'tax_query', $taxquery );
}
add_action( 'pre_get_posts', 'only_returns_matched_posts' );
I want the matched posts grouped at the top of the query with the other posts following. Is it possible to either:
- use this format with a
orderby
- do 2 separate queries and merge them
- use a custom Group By SQL query
EDIT
I managed to merge 2 queries but I lose the menu_order when I apply post__in
to keep the $queryA
+ $queryB
order.
Should I get ids differently than with $query->posts
to keep original menu_order
of the queries?
function group_matched_posts_at_top( $query ) {
// Check if this is the main query and not in the admin area
if( !$query->is_main_query() || is_admin() )
return;
// Get posts with matched taxonomy + posts without taxonomy
$queryAparams = array(
'posts_per_page' => -1,
'post_type' => 'product',
'order_by' => 'menu_order',
'order' => 'ASC',
'fields' => 'ids',
'tax_query'=> array(
'relation' => 'OR',
array(
'taxonomy' => 'pa_group',
'field' => 'slug',
'terms' => 'matchedstring',
'operator' => 'IN'
),
array(
'taxonomy' => 'pa_group',
'operator' => 'NOT EXISTS'
)
)
);
// Get posts with other taxonomies
$queryBparams = array(
'posts_per_page' => -1,
'post_type' => 'product',
'order_by' => 'menu_order',
'order' => 'ASC',
'fields' => 'ids',
'tax_query'=> array(
'relation' => 'AND',
array(
'taxonomy' => 'pa_group',
'field' => 'slug',
'terms' => 'matchedstring',
'operator' => 'NOT IN'
),
array(
'taxonomy' => 'pa_group',
'operator' => 'EXISTS'
)
)
);
$queryA = new WP_Query($queryAparams);
$queryB = new WP_Query($queryBparams);
// Merging ids
$postIDs = array_merge($queryA->posts,$queryB->posts);
if(!empty($postIDs)){
$query->set('post__in', $postIDs);
$query->set('orderby', 'post__in');
}
}
add_action( 'woocommerce_product_query', 'group_matched_posts_at_top' );
EDIT2
I'll post my own answer.
I had to actually remove the 'fields' => 'ids'
parameters to keep the queries menu_order
and pluck the ids after resorting them.
tax_query
in your questiontax_query
is formated, but it is an invalid code because I thinkgroupby
is not a valid property in this context. It would beorderby
, which doesn't accept the same array as atax_query
. Do you get the idea?