I'm trying to order the woocommerce products by the existence of a specific meta key, in particular: I need to display first the products that have this meta key, and the all the products that doesn't have the meta key "price_sale_custom", so I wrote this code:
$args['meta_query'][] = [
'relation' => 'OR',
'promo_exists' => [
'key' => 'price_sale_custom',
'compare' => 'EXISTS',
],
'promo_not_exists' => [
'key' => 'price_sale_custom',
'compare' => 'NOT EXISTS',
],
];
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'price_sale_custom';
$args['order'] = 'DESC';
the main issue is that I get only the products that have the meta key "price_sale_custom" but not the others that doesn't have it. What I did wrong?
update
$args['meta_query'][] = [
'relation' => 'OR',
[
'key' => 'price_sale_custom',
'compare' => 'EXISTS',
],
[
'key' => 'price_sale_custom',
'compare' => 'NOT EXISTS',
],
];
$args['orderby'] = [
'price_sale_custom' => 'DESC',
'date' => 'DESC'
];
I'm trying to order the woocommerce products by the existence of a specific meta key, in particular: I need to display first the products that have this meta key, and the all the products that doesn't have the meta key "price_sale_custom", so I wrote this code:
$args['meta_query'][] = [
'relation' => 'OR',
'promo_exists' => [
'key' => 'price_sale_custom',
'compare' => 'EXISTS',
],
'promo_not_exists' => [
'key' => 'price_sale_custom',
'compare' => 'NOT EXISTS',
],
];
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'price_sale_custom';
$args['order'] = 'DESC';
the main issue is that I get only the products that have the meta key "price_sale_custom" but not the others that doesn't have it. What I did wrong?
update
$args['meta_query'][] = [
'relation' => 'OR',
[
'key' => 'price_sale_custom',
'compare' => 'EXISTS',
],
[
'key' => 'price_sale_custom',
'compare' => 'NOT EXISTS',
],
];
$args['orderby'] = [
'price_sale_custom' => 'DESC',
'date' => 'DESC'
];
The meta_key
parameter tells WP_Query
to only return posts that have the price_sale_custom
meta data. Remove that first, and then change orderby
to reference the meta_query
values:
This is something that WordPress added support for in 4.2: https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
https://stackoverflow.com/questions/17745334/how-to-order-by-multiple-meta-keys