I aim to prioritize certain products within the product loop by displaying specific ones first, identified by a custom field called ‘Is top product?’ with a meta value of 1 when checked.
For instance, if I have a pool of 50
products, and I designate 5
as Is top product?
, I want these 5
to appear at the forefront of my custom loop query. Subsequently, I wish to display the remaining 45
products in ascending order
based on their prices
.
Although My code works fine for showing the top products, but I’m struggling to get the others sorted by price.
1st version
$meta_query = array(
'relation' => 'OR',
array(
'key' => 'is_top_product',
'value' => '1',
'compare' => '=',
),
array(
'key' => 'is_top_product',
'compare' => 'NOT EXISTS',
),
);
$woo_products_args['orderby'] = array(
'is_top_product' => 'DESC', // Top products first
'_price' => 'ASC', // Then sort by price
);
$woo_products_args['post_type'] = 'product';
$woo_products_args['posts_per_page'] = '12;
$woo_products_args['meta_query'] = $meta_query;
$woo_products_args['post_status'] = 'publish';
$woo_products = new WP_Query( $woo_products_args );
2nd versions just like the first one, but with this added.
$woo_products_args['meta_key'] = '_price';
3rd version same as fisrt one just change in orderby
$woo_products_args['orderby'] = array(
'meta_value_num' => 'DESC', // Top products first
'meta_value_num' => 'price', // Then sort by price
'orderby' => 'meta_value_num', // Meta value as numeric value
)