I have the below foreach
loop running over an array of WooCommerce products, which are queried by the below query. This outputs the products in the menu_order
, which is as expected, however what I need to do is to keep them in this order, EXCEPT products which as ‘featured products’. These should almost be ignored by the order parameter and always appear first in the foreach
loop.
Is this possible?
// Get Products
$args = array(
'status' => 'publish',
'category' => $currentCat->slug,
'orderby' => 'menu_order',
'order' => 'ASC',
'limit' => -1,
);
$productsData = wc_get_products( $args );
<? // For each product
foreach($productsData as $product): ?>
<? if( $product['isFeatured'] ): ?>
// Output featured product html here...
<? else: ?>
// Output other products HTML here...
<? endif ?>
<? endforeach ?>
2
Answers
Managed to resolve this for my needs by performing 2 separate queries, and then merging them into an array (in the desired order). This ensures one query always appears before the other, whilst each query can still respect ordering parameters such as
menu_order
.I haven’t tried this, but you could see if this works. I know this trick works with meta queries, so It might work with taxonomy queries too: the trick being to reference the tax queries by name in the orderby.
If the above doesn’t work, you can break it out into 2 different queries like so: